#' RNAi
#'
#' RNAi Package to do stuff
#'
#' @name RNAi
#'
#'

require(dplyr)

# mapper for hypergeometric distribution
# with lower.tail, return value is P[X > x], therefore x-1 as first argument
rsa.phyper.map <- function(row) {
  phyper(row[1]-1, row[2], row[3], row[4],
         lower.tail=F, log.p=T)
}

# b<-590 to 591 reaches the 1E-2180  lowest p-value limit
# a
# phyper(b, a-b, 30203, 1090, lower.tail=FALSE, log.p = TRUE)

# calculate p-values for each siRNA of a gene
# by default, return only data for the siRNA with the smallest p-value
# with full=T, all data is returned
rsa.prob <- function(x, N, full) {
  nr <- nrow(x)
  x <- x[order(x$rank),]
  a <- seq_len(nr)
  b <- x$rank
  c <- N-b
  d <- nr
  counts <- cbind(a,b,c,d)
  p <- apply(counts, 1, rsa.phyper.map)/log(10)

  if (full) {
    idx <- seq_len(nr)
  } else {
    idx <- which.min(p)
  }

  return(cbind(x, counts, p)[idx,])
}

#' rsa
#'
#'
#' @author Florian Nigsch, Gregory McAllister
#' @name rsa
#' @param rsadat data frame containing a minimum of gene id and value
#' @param gene.column column name in rsadat specifying the gene identifier
#' @param vale.column column name in rsadat specifying the value
#' @param activator boolean specifying whether the screen is an activator or inhibitor.  Activator will ranking such that numerically smaller values get lower ranks (ie are better)
#' @param full boolean specifying whether to return all objects and their associated p-values.  This will also return counts from the hypergeometric
#' @param subset boolean (T = limit data frame returned to gene identifier and LogP)
#' @return data frame
#' @references A probability-based approach for the analysis of large-scale RNAi screens
#'   Nature Methods - 4, 847 - 849 (2007), doi:10.1038/nmeth1089
#'   Paper: \url{http://www.nature.com/nmeth/journal/v4/n10/full/nmeth1089.html}
#'   SuppInfo: \url{http://www.nature.com/nmeth/journal/v4/n10/extref/nmeth1089-S1.pdf}
#'
#' @seealso \code{rsa.gnf}
#'
#' @export

rsa <- function(rsadat, activator=F, full=F, gene.column="gene", value.column="value", subset=F, drugseq=F,drugseq.ties='average') {

  switch <- ifelse(activator, -1, 1)

  if(drugseq) {
    ties.met<-drugseq.ties #default = 'average' which performs well upon manual review.
  } else {
    ties.met<-"min"
  }

  rsadat$rank <- rank(rsadat[,value.column] * switch, ties.method=ties.met)

  res <- by(rsadat, rsadat[,gene.column], rsa.prob, nrow(rsadat), full)

  res <- do.call("rbind", res)

  if(full)
    return(res)

  if (subset){
    tmp <- res[,c(gene.column,"p")]
    colnames(tmp)[2] <- "LogP"
    return(tmp)
  }else{
    tmp <- res[,!colnames(res) %in% c("rank","a","b","c","d")]
    colnames(tmp)[which(colnames(tmp)=="p")] <- "LogP"
    return(tmp)
  }

}

q1q3 <- function(dat){
  result <- quantile(dat$my_value,probs=c(0.25,0.75),na.rm=T)
  return (c(result[1],result[2]))
}

q0q1q3q4 <-function(dat){
  result <- quantile(dat$my_value,probs=c(0,0.25,0.75,1),na.rm=T)
  return (c(result[1],result[2],result[3],result[4]))
}

logq0q1q2q3q4<-function(dat){
  result <- quantile(dat$my_logvalue,probs=c(0,0.25,0.5,0.75,1),na.rm=T)
  return (c(result[1],result[2],result[3],result[4],result[5]))
}

#' score.screen.ZY.RQz
#'
#' Generate gene level scores for a single RNAi screen.  Runs RSA in both directions and generates Q1/Q3 per gene.
#'
#' @name score.screen
#' @param x data frame containing at least a gene column and score column
#' @param gene.column column name in rsadat specifying the gene identifier
#' @param vale.column column name in rsadat specifying the value
#' @param both.directions boolean indicating whether to calculate "RSA Up" as well
#'
#' @export

score.screen.ZY.RQz <- function(data,gene.column="gene",value.column="value",log.column="Log2FoldChange",drugseq=F,drugseq.ties='average') {
  if(drugseq){print('RSA setup for DRUG-seq: ties.methods is set to average in place of min in CRISPR/siRNA screens')}
  x.rsa.d <- rsa(data,gene.column=gene.column,value.column=value.column,subset=T,drugseq=drugseq,drugseq.ties=drugseq.ties)
  x.rsa.d <- unique(x.rsa.d[,c(gene.column,"LogP")])
  colnames(x.rsa.d)[2] <- "logP_RSA_Down"

  x.rsa.u <- rsa(data,gene.column=gene.column,value.column=value.column,subset=T,activator=T,drugseq=drugseq,drugseq.ties=drugseq.ties)
  x.rsa.u <- unique(x.rsa.u[,c(gene.column,"LogP")])
  colnames(x.rsa.u)[2] <- "logP_RSA_Up"

  #y <- ddply(data,gene.column,function(x) { quantile(x[,value.column],probs=c(0.25,0.75))})
  # remove plyr dependency - there are probably more elegant code for this thou...
  data$my_gene <- data[,gene.column]
  data$my_value <- data[,value.column]
  data$my_logvalue<- data[,log.column]
  data2<- select(data,my_gene,my_logvalue)
  data <- select(data,my_gene,my_value)
  #updated from q1q3 to q0q1q3q4 on 2017-11-20
  #y <- by(data,data$my_gene,q1q3)
  y <- by(data,data$my_gene,q0q1q3q4)
  y2<- by(data2,data2$my_gene,logq0q1q2q3q4)

  y <- as.data.frame(do.call(rbind,y))
  y$gene<-rownames(y)

  y2 <- as.data.frame(do.call(rbind,y2))
  y2$gene<-rownames(y2)

  #y <- y[c(5,1,2)]
  #colnames(y) <- c(gene.column,"rz_score_Q1","rz_score_Q3")
  #updated from above on 2017-11-20
  y <- y[c(5,1,2,3,4)]
  colnames(y) <- c(gene.column,"rz_score_min","rz_score_Q1","rz_score_Q3","rz_score_max")

  y2 <- y2[c(6,1,2,3,4,5)]
  colnames(y2) <- c(gene.column,"Min log2FoldChange","Q1 log2FoldChange","Median log2FoldChange","Q3 log2FoldChange","Max log2FoldChange")

  all <- merge(x.rsa.d,x.rsa.u,by=gene.column,all=T)

  zN<-by(data,data$my_gene,tally)
  zN <- as.data.frame(do.call(rbind,zN))
  zN$gene<-rownames(zN)
  zN <- zN[c(2,1)]
  colnames(zN)<-c(gene.column,"N")

  data_temp_D<-subset(data,data$my_value<=(-2.0))
  data_temp_D3<-subset(data,data$my_value<=(-3.0))
  data_temp_D4<-subset(data,data$my_value<=(-4.0))

  if(dim(data_temp_D)[1]==0) {
  } else {
    zD<-by(data_temp_D,data_temp_D$my_gene,tally)
    zD <- as.data.frame(do.call(rbind,zD))
    zD$gene<-rownames(zD)
    zD <- zD[c(2,1)]
    colnames(zD)<-c(gene.column,"z2_count_Down")
  }

  if(dim(data_temp_D3)[1]==0) {
  } else {
    zD3<-by(data_temp_D3,data_temp_D3$my_gene,tally)
    zD3 <- as.data.frame(do.call(rbind,zD3))
    zD3$gene<-rownames(zD3)
    zD3 <- zD3[c(2,1)]
    colnames(zD3)<-c(gene.column,"z3_count_Down")
  }

  if(dim(data_temp_D4)[1]==0) {
  } else {
    zD4<-by(data_temp_D4,data_temp_D4$my_gene,tally)
    zD4 <- as.data.frame(do.call(rbind,zD4))
    zD4$gene<-rownames(zD4)
    zD4 <- zD4[c(2,1)]
    colnames(zD4)<-c(gene.column,"z4_count_Down")
  }

  data_temp_U<-subset(data,data$my_value>=(2.0))
  data_temp_U3<-subset(data,data$my_value>=(3.0))
  data_temp_U4<-subset(data,data$my_value>=(4.0))

  if(dim(data_temp_U)[1]==0) {
  } else {
    zU<-by(data_temp_U,data_temp_U$my_gene,tally)
    zU <- as.data.frame(do.call(rbind,zU))
    zU$gene<-rownames(zU)
    zU <- zU[c(2,1)]
    colnames(zU)<-c(gene.column,"z2_count_Up")
  }

  if(dim(data_temp_U3)[1]==0) {
  } else {
    zU3<-by(data_temp_U3,data_temp_U3$my_gene,tally)
    zU3 <- as.data.frame(do.call(rbind,zU3))
    zU3$gene<-rownames(zU3)
    zU3 <- zU3[c(2,1)]
    colnames(zU3)<-c(gene.column,"z3_count_Up")
  }

  if(dim(data_temp_U4)[1]==0) {
  } else {
    zU4<-by(data_temp_U4,data_temp_U4$my_gene,tally)
    zU4 <- as.data.frame(do.call(rbind,zU4))
    zU4$gene<-rownames(zU4)
    zU4 <- zU4[c(2,1)]
    colnames(zU4)<-c(gene.column,"z4_count_Up")
  }

  all <- merge(all,y,by=gene.column,all=T)
  all <- merge(all,y2,by=gene.column,all=T)

  all <- merge(all,zN,by=gene.column,all=T)

  if(dim(data_temp_D)[1]==0) {
    all$z2_count_Down<-(0)
  } else {
    all <- merge(all,zD,by=gene.column,all=T)
  }

  if(dim(data_temp_U)[1]==0) {
    all$z2_count_Up<-(0)
  } else {
    all <- merge(all,zU,by=gene.column,all=T)
  }

  if(dim(data_temp_D3)[1]==0) {
    all$z3_count_Down<-(0)
  } else {
    all <- merge(all,zD3,by=gene.column,all=T)
  }

  if(dim(data_temp_U3)[1]==0) {
    all$z3_count_Up<-(0)
  } else {
    all <- merge(all,zU3,by=gene.column,all=T)
  }

  if(dim(data_temp_D4)[1]==0) {
    all$z4_count_Down<-(0)
  } else {
    all <- merge(all,zD4,by=gene.column,all=T)
  }

  if(dim(data_temp_U4)[1]==0) {
    all$z4_count_Up<-(0)
  } else {
    all <- merge(all,zU4,by=gene.column,all=T)
  }

  all[is.na(all$z2_count_Down),'z2_count_Down']<-0
  all[is.na(all$z2_count_Up),'z2_count_Up']<-0
  all[is.na(all$z3_count_Down),'z3_count_Down']<-0
  all[is.na(all$z3_count_Up),'z3_count_Up']<-0
  all[is.na(all$z4_count_Down),'z4_count_Down']<-0
  all[is.na(all$z4_count_Up),'z4_count_Up']<-0

  invisible(all)
}


#' @name cMGL.multi
#' @rdname  cMGL.multi
#' @title d-dimensional MGL and survival MGL copula
#' @description
#' Density, distribution function, and random generation for the MGL and survival MGL copula.
#'
#' @param u d-dimensional matrix
#' @param d d-dimensional
#' @param pars copula parameter, denoted by \eqn{\delta>0}.
#' @param log logical; if TRUE, probabilities/densities p are returned as log(p).
#' @param n number of observations. If length(n) > 1, the length is taken to be the number required.
#' @importFrom stats qbeta
#' @importFrom stats pbeta
#' @importFrom stats runif
#' @importFrom stats pgamma
#' @md
#' @return
#' * \code{dcMGL.multi}, \code{pcMGL.multi} and \code{rcMGL.multi} gives values of Density, distribution function, and random generation for the d-dimensional MGL copula with copula parameter \eqn{\delta>0}.
#' * \code{dcMGL180.multi}, \code{pcMGL180.multi} and \code{rcMGL180.multi} gives values of Density, distribution function, and random generation for the d-dimensional MGL copula with copula parameter \eqn{\delta>0}.
NULL

#' @rdname cMGL.multi
#' @export
#' @examples
#'
#'
#' dcMGL.multi(u = cbind(c(0.6, 0.1, 0.5), c(0.3, 0.9, 0.2)), pars = 2, log = FALSE)
#'
#' dcMGL.multi(u = cbind(c(0.6, 0.1), c(0.3, 0.9), c(0.5, 0.6)), pars = 2, log = TRUE)
dcMGL.multi <- function(u, pars, log = FALSE) {
  # coding as a matrix
  dim <- ncol(u)
  a <- 1 / pars[1]
  q <- (qbeta(1 - u, shape1 = 0.5, shape2 = a) / (1 - qbeta(1 - u, shape1 = 0.5, shape2 = a)))
  logdc <- 0
  for (i in seq_len(nrow(u))) {
    logdc[i] <- (dim - 1) * lgamma(a) + lgamma(a + dim / 2) - dim * lgamma(a + 0.5) + (a + 0.5) * sum(log(q[i, ] + 1)) - (a + dim / 2) * log(sum(q[i, ]) + 1)
  }
  dc <- exp(logdc)
  dc[which(q == Inf)] <- 0
  if (log == TRUE) {
    out <- logdc
  } else {
    out <- dc
  }
  return(out)
}

#' @rdname cMGL.multi
#' @export
#' @examples
#' \dontrun{
#'
#' dcMGL180.multi(u = cbind(c(0.6, 0.1, 0.5), c(0.3, 0.9, 0.2)), pars = 2, log = FALSE)
#'
#' dcMGL180.multi(u = cbind(c(0.6, 0.1), c(0.3, 0.9), c(0.5, 0.6)), pars = 2, log = TRUE)
#' }
dcMGL180.multi <- function(u, pars, log = FALSE) {
  dcMGL.multi(u = 1 - u, pars = pars, log = log)
}

#' @rdname cMGL.multi
#' @export
#' @examples
#' # 2-dim MGL copula
#' pcMGL.multi(u = cbind(c(0.5, 0.5), c(0.01, 0.9)), pars = 3)
#' # 3-dim MGL copula
#' pcMGL.multi(u = cbind(c(0, 0.2, 0.5), c(0.5, 0.2, 0.5), c(0.01, 0.5, 0.9)), pars = 3)
pcMGL.multi <- function(u, pars) {
  # dim <- ncol(u)
  a <- 1 / pars[1]

  q <- (qbeta(1 - u, shape1 = 0.5, shape2 = a) / (1 - qbeta(1 - u, shape1 = 0.5, shape2 = a)))
  z <- 0
  for (i in seq_len(nrow(u))) {
    if (any(q[i, ] %in% Inf)) {
      z[i] <- 0
    } else {
      temp <- as.vector(q[i, ])
      fin <- function(theta) { # rely on a
        # theta <- as.vector()
        m <- pracma::erfc((temp * theta)^0.5)
        k <- base::prod(m)
        out <- k * theta^(a - 1) * exp(-theta) / gamma(a)
        out
      }
      fin <- Vectorize(fin)
      z[i] <- as.numeric(pracma::integral(
        fun = fin,
        xmin = 0,
        xmax = Inf, method = "Clenshaw"
      ))
    }
  }
  return(z) # rely on k
}

#' @rdname cMGL.multi
#' @export
#' @examples
#' pcMGL180.multi(u = cbind(c(0.5, 0.5), c(0.01, 0.9)), pars = 3)
pcMGL180.multi <- function(u, pars) {
  # dim <- ncol(u)
  delta <- pars[1]

  q <- (qbeta(u, shape1 = 0.5, shape2 = delta) / (1 - qbeta(u, shape1 = 0.5, shape2 = delta)))
  z <- 0
  for (i in seq_len(nrow(u))) {
    # if(any(q[i,] %in% Inf)) {
    #   z[i] <- 0
    # } else {
    temp <- as.vector(q[i, ])
    fin <- function(theta) { # rely on theta
      m <- pgamma(q = temp / theta, shape = 0.5, scale = 1)
      k <- base::prod(m)
      out <- k * theta^(-(delta + 1)) * exp(-1 / theta) / gamma(delta)
      out
    }
    fin <- Vectorize(fin)

    z[i] <- as.numeric(pracma::integral(
      fun = fin,
      xmin = 0,
      xmax = Inf, method = "Clenshaw"
    ))
  }
  return(z)
}
# pcMGL180.multi(u = cbind(c(0.5, 0.1), c(0.9, 0.1)), pars = 1.5)
# pcMGB2.bivar(u1 = c(0.5, 0.1), u2 = c(0.9, 0.1), pars1 = 0.5, pars2 = 0.5, pars3 = 1.5)

#' @rdname cMGL.multi
#' @export
#' @examples
#' Usim <- rcMGL.multi(n = 1000, d = 2, pars = 1)
#' plot(Usim)
rcMGL.multi <- function(n, d, pars) {
  a <- 1 / pars
  dseq <- seq(1:(d - 1))
  anew <- c(a, a + dseq / 2)
  Iinv_trans <- function(u, a) {
    qbeta(1 - u, shape1 = 0.5, shape2 = a) / (1 - qbeta(1 - u, shape1 = 0.5, shape2 = a))
  }
  umat <- matrix(data = runif(n * d, min = 0, max = 1), nrow = n, ncol = d)
  mmat <- qmat <- zmat <- Usim <- matrix(data = 0, nrow = n, ncol = d)

  for (j in seq_len(ncol(umat))) {
    qmat[, j] <- Iinv_trans(umat[, j], a = anew[j]) # column j denots the qj
  }

  mmat[, 1] <- qmat[, 1]
  mmat[, 2] <- (1 + mmat[, 1]) * qmat[, 2]
  if (d > 2) {
    for (j in 3:ncol(umat)) {
      tempmat <- mmat[, (1):(ncol(umat) - 1)]
      if (n == 1) {
        msum <- sum(tempmat)
      } else {
        msum <- apply(tempmat, MARGIN = 1, sum)
      }
      mmat[, j] <- (1 + msum) * qmat[, j]
    }
  }

  for (j in seq_len(ncol(zmat))) {
    k <- mmat[, j] / (mmat[, j] + 1)
    Usim[, j] <- 1 - pbeta(k, shape1 = 0.5, shape2 = a)
  }

  return(Usim)
}

#' @rdname cMGL.multi
#' @export
#' @examples
#' Usim <- rcMGL180.multi(n = 1000, d = 2, pars = 1)
#' plot(Usim)
rcMGL180.multi <- function(n, d, pars) {
  1 - rcMGL.multi(n = n, d = d, pars = pars)
}


#' Plot annual MSY
#'
#' Plot values associated with MSY using year-specific inputs.
#' @param asap name of the variable that read in the asap.rdat file
#' @param a1 list file produced by grab.aux.files function
#' @param save.plots save individual plots
#' @param od output directory for plots and csv files
#' @param plotf type of plot to save
#' @export

PlotAnnualMSY <- function(asap,a1,save.plots,od,plotf){

  h.vals <- asap$SR.annual.parms$steepness.vec
  recr.par <- h.vals

  if (asap$control.parms$phases$phase.steepness>0 & max(h.vals)<1 ) { # test to make sure steepness was estimated

    nages<- asap$parms$nages
    nyears <- asap$parms$nyears
    years <- seq(asap$parms$styr,asap$parms$endyr)
    if (asap$options$isfecund == 1){
      fec.age <- asap$WAA.mats$WAA.ssb / asap$WAA.mats$WAA.ssb # matrix of 1s
    }else{
      fec.age <- asap$WAA.mats$WAA.ssb
    }
    mat.age <- asap$maturity
    wgt.age <- asap$WAA.mats$WAA.catch.all
    M.age <- asap$M.age
    sel.mat <- asap$F.age/apply(asap$F.age,1,max)

    spawn.time <- asap$options$frac.yr.spawn

    ahat.vals <- 4*h.vals/(1-h.vals)
    R0.vals <- asap$SR.annual.parms$R0.vec
    sr0.vals <- asap$SR.annual.parms$s.per.r.vec
    MSY.soln <- matrix(NA, nrow=9, ncol=nyears)
    rownames(MSY.soln) <- c("Fmsy", "MSY", "SPRmsy", "SSBmsy", "Rmsy", "YPRmsy",
                            "Rel.SSBmsy", "Rel.Rmsy", "Conv.Code")
    colnames(MSY.soln) <-  seq(asap$parms$styr, asap$parms$endyr)

    for (i in 1:nyears) {
      F.start=0.25
      get.yield.f.min <- function(F.start) {
        temp.spr = s.per.recr(nages=nages, fec.age=fec.age[i,], mat.age=mat.age[i,], M.age= M.age[i,], F.mult=F.start, sel.age=sel.mat[i,], spawn.time=spawn.time)
        temp.ypr = ypr(nages=nages, wgt.age=wgt.age[i,], M.age=M.age[i,],  F.mult=F.start, sel.age=sel.mat[i,] )
        temp.SSB = ssb.eq( recr.par=ahat.vals[i], R0.BH=R0.vals[i], spr=temp.spr, spr0=sr0.vals[i], is.steepness=F )
        yield = temp.ypr*temp.SSB/temp.spr           #harvest in weight
        yy=-1*yield
        return(yy)
      }   # end get.yield.f.min function

      F.nlmin <- nlminb( start=F.start , objective=get.yield.f.min, lower=0.01, upper=3.0,
                         control=list(eval.max=500, iter.max=200  )   )

      MSY.soln[1, i] <- F.nlmin$par  #Fmsy
      MSY.soln[2, i] <- -1*F.nlmin$objective #MSY

      # calculate other MSY quantities
      spr.nlmin <- s.per.recr(nages=nages, fec.age=fec.age[i,], mat.age=mat.age[i,], M.age= M.age[i,], F.mult=F.nlmin$par, sel.age=sel.mat[i,], spawn.time=spawn.time)
      MSY.soln[3, i] <- spr.nlmin/sr0.vals[i] #SPRmsy

      ssb.nlmin <- ssb.eq( recr.par=ahat.vals[i], R0.BH=R0.vals[i], spr=spr.nlmin, spr0=sr0.vals[i], is.steepness=F )
      MSY.soln[4, i] <-  ssb.nlmin #SSBmsy

      Rmsy.nlmin <- bev.holt.alpha(S=ssb.nlmin,R0=R0.vals[i],recr.par=ahat.vals[i],spr0=sr0.vals[i])
      MSY.soln[5,i ] <- Rmsy.nlmin #Rmsy

      ypr.nlmin <- ypr(nages=nages, wgt.age=wgt.age[i,], M.age=M.age[i,],  F.mult=F.nlmin$par, sel.age=sel.mat[i,] )
      MSY.soln[6,i ] <- ypr.nlmin #YPRmsy

      rel.ssb.nlmin <- ssb.nlmin/(R0.vals[i]*sr0.vals[i])
      MSY.soln[7, i] <-  rel.ssb.nlmin #SSBmsy/SSB0

      MSY.soln[8, i] <- Rmsy.nlmin/R0.vals[i] #Rmsy/R0

      MSY.soln[9, i] <-  F.nlmin$convergence  #code=0 indicates convergence
    }  # end i-loop over nyears

    f.hist <- hist(MSY.soln[1,], plot=F)
    MSY.hist <- hist(MSY.soln[2,], plot=F)
    R.hist <- hist(MSY.soln[5,], plot=F )
    S.hist <- hist(MSY.soln[4,], plot=F )

    h.hist <- hist(h.vals, plot=F)
    SPR.hist <- hist(MSY.soln[3,], plot=F)
    R0.hist <- hist(R0.vals, plot=F )
    S0.hist <- hist(asap$SR.annual.parms$S0.vec, plot=F )

    par(mfrow=c(2,2), mar=c(4,4,2,2), oma=c(0,0,2,0) )

    plot(f.hist$mids, f.hist$counts, xlab="Full F", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(f.hist$counts))  )
    lines(f.hist$mids, f.hist$counts, lwd=2)
    plot(S.hist$mids, S.hist$counts, xlab="SSB.MSY", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(S.hist$counts))  )
    lines(S.hist$mids, S.hist$counts, lwd=2)
    plot(MSY.hist$mids, MSY.hist$counts, xlab="MSY", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(MSY.hist$counts)) )
    lines(MSY.hist$mids, MSY.hist$counts, lwd=2)
    plot(R.hist$mids, R.hist$counts, xlab="R.MSY", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(R.hist$counts))  )
    lines(R.hist$mids, R.hist$counts, lwd=2)
    title (paste0("Annual MSY Reference Points (from S-R curve)"), outer=T, line=-1 )
    if (save.plots) savePlot(paste0(od, "MSY.4panel.hist1.", plotf), type=plotf)

    plot(h.hist$mids, h.hist$counts, xlab="steepness", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(h.hist$counts))  )
    lines(h.hist$mids, h.hist$counts, lwd=2)
    plot(S0.hist$mids, S0.hist$counts, xlab="SSB0", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(S0.hist$counts))  )
    lines(S0.hist$mids, S0.hist$counts, lwd=2)
    plot(SPR.hist$mids, SPR.hist$counts, xlab="SPR.MSY", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(SPR.hist$counts)) )
    lines(SPR.hist$mids, SPR.hist$counts, lwd=2)
    plot(R0.hist$mids, R0.hist$counts, xlab="R0", ylab="Frequency", type='h', lwd=2, ylim=c(0, max(R0.hist$counts))  )
    lines(R0.hist$mids, R0.hist$counts, lwd=2)
    title (paste0("Annual MSY Reference Points (from S-R curve)"), outer=T, line=-1 )
    if (save.plots) savePlot(paste0(od, "MSY.4panel.hist2.", plotf), type=plotf)

    par(mfrow=c(1,1), mar=c(4,4,2,2) )

    h.order <- order(h.vals)
    steep.spr <- cbind(h.vals[h.order], MSY.soln[3,h.order])

    plot(steep.spr[,1], steep.spr[,2], xlab="Steepness", ylab="SPR.MSY", xlim=c(0.2,1), ylim=c(0,1),
         type='p', pch=16, col='blue3' )
    points(h.vals[1], MSY.soln[3,1], pch=16, cex=1.5, col="green3")
    points(h.vals[nyears], MSY.soln[3,nyears], pch=16, cex=1.5, col="orange2")
    legend('top', legend=c("First Year", "Last Year"), pch=c(16,16), col=c("green3", "orange2") )
    title (paste0("Annual Steepness and SPR.MSY (from S-R curve)"), outer=T, line=-1 )

    if (save.plots) savePlot(paste0(od, "MSY.h.vs.SPR.", plotf), type=plotf)

    plot(years, MSY.soln[1,], xlab="Year", ylab="Full F at MSY", ylim=1.1*c(0, max(MSY.soln[1,])), type='l', lwd=2  )
    points(years, MSY.soln[1,], pch=10)
    title (paste0("Annual MSY Reference Points (from S-R curve)"), outer=T, line=-1 )

    if (save.plots) savePlot(paste0(od, "Annual.Fmsy.", plotf), type=plotf)

    plot(years, MSY.soln[2,], xlab="Year", ylab="MSY", ylim=1.1*c(0, max(MSY.soln[2,])), type='l', lwd=2  )
    points(years, MSY.soln[2,], pch=10)
    title (paste0("Annual MSY Reference Points (from S-R curve)"), outer=T, line=-1 )

    if (save.plots) savePlot(paste0(od, "Annual.MSY.", plotf), type=plotf)

    plot(years, MSY.soln[3,], xlab="Year", ylab="%SPR at MSY", ylim=1.1*c(0, 1), type='l', lwd=2  )
    points(years, MSY.soln[3,], pch=10)
    title (paste0("Annual MSY Reference Points (from S-R curve)"), outer=T, line=-1 )

    if (save.plots) savePlot(paste0(od, "Annual.SPR.MSY.", plotf), type=plotf)

    plot(years, MSY.soln[4,], xlab="Year", ylab="SSB at MSY", ylim=1.1*c(0, max(MSY.soln[4,])), type='l', lwd=2  )
    points(years, MSY.soln[4,], pch=10)
    title (paste0("Annual MSY Reference Points (from S-R curve)"), outer=T, line=-1 )

    if (save.plots) savePlot(paste0(od, "Annual.SSB.MSY.", plotf), type=plotf)

    plot(years, MSY.soln[5,], xlab="Year", ylab="Recruitment at MSY", ylim=1.1*c(0, max(MSY.soln[5,])), type='l', lwd=2  )
    points(years, MSY.soln[5,], pch=10)
    title (paste0("Annual MSY Reference Points (from S-R curve)"),
           outer=T, line=-1 )

    if (save.plots) savePlot(paste0(od, "Annual.Recr.MSY.", plotf), type=plotf)

    frep1 <-asap$options$Freport.agemin
    frep2 <-asap$options$Freport.agemax
    if (frep1==frep2) freport <-MSY.soln[1,frep1:frep2]*sel.mat[,frep1:frep2]
    if (frep2>frep1) freport <-apply(MSY.soln[1,frep1:frep2]*sel.mat[,frep1:frep2],1,mean)
    freport.label <- paste0("Freport_",frep1,"-",frep2)
    MSY.soln<-  rbind(MSY.soln, freport)
    rownames(MSY.soln) <-
      c("Fmsy", "MSY", "SPRmsy", "SSBmsy", "Rmsy", "YPRmsy",
        "Rel.SSBmsy", "Rel.Rmsy", "Conv.Code",paste0("Freport_",frep1,"-",frep2))

    asap.name <- a1$asap.name
    write.csv( t(MSY.soln), file=paste0(od, "MSY.soln.values_", asap.name, ".csv"), row.names=T )

  } # end test for steepness phase>0

  return()
}  # end function


###############################################################################
###############################################################################
#
#
#     Project: An exposure weighted warming
#     Team: Marcin Gajewski, Salma Al-Zadjali, Yasna Palmeiro Silva
#
#     Analysis of UKCP18 dataset for
#       - Mean air temperature at 1.5m (°C)
#       - Maximum air temperature at 1.5m (°C)
#       - Minimum air temperature at 1.5m (°C)
#
#     In order to obtain meaningful results, we used monthly data.
#
#     Based on the data, we calculated temperature anomalies, considering
#     a historical baseline of 20 years (1980-2000).
#
#     In order to calculate population-weighted average anomalies,
#     we used population estimations from 2000 onward.
#
###############################################################################
###############################################################################

# Libraries we need
library(raster)
library(sf)
library(sp)
library(ncdf4)
library(ggplot2)
library(rgdal)
library(rlang)
library(dplyr)
library(lubridate)
library(zoo)
library(stringr)
library(tidyverse) #include readr
library(ggthemes)
library(ggpubr)

###############################################################################
#   SHAPEFILES
###############################################################################

# We need: ukcp18-uk-land-country-hires
uk_borders <- st_read("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/ukcp-spatial-files/spatial-files/ukcp18-uk-land-country-hires/ukcp18-uk-land-country-hires.shp")
as_Spatial(uk_borders)
plot(uk_borders)

uk_borders$geo_region # "Channel Islands", "England", "Isle of Man", "Northern Ireland", "Scotland", "Wales"

# In order to obtain some data for each region, we create subsets of polygons
Cha_borders <- uk_borders[uk_borders$geo_region == "Channel Islands",]
Eng_borders <- uk_borders[uk_borders$geo_region == "England",]
Isl_borders <- uk_borders[uk_borders$geo_region == "Isle of Man",]
NIr_borders <- uk_borders[uk_borders$geo_region == "Northern Ireland",]
Sco_borders <- uk_borders[uk_borders$geo_region == "Scotland",]
Wal_borders <- uk_borders[uk_borders$geo_region == "Wales",]

###############################################################################
#   POPULATION
###############################################################################

# Dataset: SSP5 population projections on the OSGB grid
pop.nc <- nc_open("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/population/population-projections-ssp5-total.nc")
print(pop.nc)
names(pop.nc$var) #"crs" "ssp"

pop <- brick("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/population/population-projections-ssp5-total.nc")
pop   # This dataset has 11 years: 2000, 2010, 2020, 2030, 2040, 2050, 2060, 2070, 2080, 2090, 2100.
      # We checked that resolution, extent, and CRS were the same for temperature projections.
      # This dataset contains absolute number of people living per grid.

#################################################
# Manipulation & interpolation
#################################################

# Masking (M) and cropping according to uk_borders
popM <- mask(pop, uk_borders) %>% crop(uk_borders)

# Checking a time series of population
pop_TS <- c(cellStats(popM, sum, na.rm=T))
pop_TS <- ts(pop_TS)
plot(pop_TS)    # Population estimation grows in a approximately linear fashion.

# We can linearly interpolate years between given years
# formula for linear interpolation: P(T) = P1 + [(P2-P1)*(T-T1)/(T2-T1)]
# Interpolation is done decade by decade to preserve some different growth rates.

UKpop2000_2100 <- brick(nrows=109, ncols=55, xmn=0, xmx=660000, ymn=-84000, ymx=1224000 , nl=81)

UKpop2000_2100[[1]] <- popM[[1]] #2000
UKpop2000_2100[[2]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2001-2000)) / (2010-2000))
UKpop2000_2100[[3]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2002-2000)) / (2010-2000))
UKpop2000_2100[[4]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2003-2000)) / (2010-2000))
UKpop2000_2100[[5]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2004-2000)) / (2010-2000))
UKpop2000_2100[[6]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2005-2000)) / (2010-2000))
UKpop2000_2100[[7]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2006-2000)) / (2010-2000))
UKpop2000_2100[[8]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2007-2000)) / (2010-2000))
UKpop2000_2100[[9]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2008-2000)) / (2010-2000))
UKpop2000_2100[[10]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2009-2000)) / (2010-2000))
UKpop2000_2100[[11]] <- popM[[2]] #2010
UKpop2000_2100[[12]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2011-2010)) / (2020-2010))
UKpop2000_2100[[13]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2012-2010)) / (2020-2010))
UKpop2000_2100[[14]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2013-2010)) / (2020-2010))
UKpop2000_2100[[15]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2014-2010)) / (2020-2010))
UKpop2000_2100[[16]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2015-2010)) / (2020-2010))
UKpop2000_2100[[17]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2016-2010)) / (2020-2010))
UKpop2000_2100[[18]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2017-2010)) / (2020-2010))
UKpop2000_2100[[19]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2018-2010)) / (2020-2010))
UKpop2000_2100[[20]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2019-2010)) / (2020-2010))
UKpop2000_2100[[21]] <- popM[[3]] #2020
UKpop2000_2100[[22]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2021-2020)) / (2030-2020))
UKpop2000_2100[[23]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2022-2020)) / (2030-2020))
UKpop2000_2100[[24]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2023-2020)) / (2030-2020))
UKpop2000_2100[[25]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2024-2020)) / (2030-2020))
UKpop2000_2100[[26]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2025-2020)) / (2030-2020))
UKpop2000_2100[[27]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2026-2020)) / (2030-2020))
UKpop2000_2100[[28]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2027-2020)) / (2030-2020))
UKpop2000_2100[[29]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2028-2020)) / (2030-2020))
UKpop2000_2100[[30]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2029-2020)) / (2030-2020))
UKpop2000_2100[[31]] <- popM[[4]] #2030
UKpop2000_2100[[32]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2031-2030)) / (2040-2030))
UKpop2000_2100[[33]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2032-2030)) / (2040-2030))
UKpop2000_2100[[34]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2033-2030)) / (2040-2030))
UKpop2000_2100[[35]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2034-2030)) / (2040-2030))
UKpop2000_2100[[36]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2035-2030)) / (2040-2030))
UKpop2000_2100[[37]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2036-2030)) / (2040-2030))
UKpop2000_2100[[38]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2037-2030)) / (2040-2030))
UKpop2000_2100[[39]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2038-2030)) / (2040-2030))
UKpop2000_2100[[40]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2039-2030)) / (2040-2030))
UKpop2000_2100[[41]] <- popM[[5]] #2040
UKpop2000_2100[[42]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2041-2040)) / (2050-2040))
UKpop2000_2100[[43]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2042-2040)) / (2050-2040))
UKpop2000_2100[[44]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2043-2040)) / (2050-2040))
UKpop2000_2100[[45]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2044-2040)) / (2050-2040))
UKpop2000_2100[[46]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2045-2040)) / (2050-2040))
UKpop2000_2100[[47]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2046-2040)) / (2050-2040))
UKpop2000_2100[[48]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2047-2040)) / (2050-2040))
UKpop2000_2100[[49]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2048-2040)) / (2050-2040))
UKpop2000_2100[[50]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2049-2040)) / (2050-2040))
UKpop2000_2100[[51]] <- popM[[6]] #2050
UKpop2000_2100[[52]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2051-2050)) / (2060-2050))
UKpop2000_2100[[53]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2052-2050)) / (2060-2050))
UKpop2000_2100[[54]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2053-2050)) / (2060-2050))
UKpop2000_2100[[55]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2054-2050)) / (2060-2050))
UKpop2000_2100[[56]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2055-2050)) / (2060-2050))
UKpop2000_2100[[57]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2056-2050)) / (2060-2050))
UKpop2000_2100[[58]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2057-2050)) / (2060-2050))
UKpop2000_2100[[59]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2058-2050)) / (2060-2050))
UKpop2000_2100[[60]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2059-2050)) / (2060-2050))
UKpop2000_2100[[61]] <- popM[[7]] #2060
UKpop2000_2100[[62]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2061-2060)) / (2070-2060))
UKpop2000_2100[[63]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2062-2060)) / (2070-2060))
UKpop2000_2100[[64]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2063-2060)) / (2070-2060))
UKpop2000_2100[[65]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2064-2060)) / (2070-2060))
UKpop2000_2100[[66]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2065-2060)) / (2070-2060))
UKpop2000_2100[[67]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2066-2060)) / (2070-2060))
UKpop2000_2100[[68]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2067-2060)) / (2070-2060))
UKpop2000_2100[[69]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2068-2060)) / (2070-2060))
UKpop2000_2100[[70]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2069-2060)) / (2070-2060))
UKpop2000_2100[[71]] <- popM[[8]] #2070
UKpop2000_2100[[72]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2071-2070)) / (2080-2070))
UKpop2000_2100[[73]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2072-2070)) / (2080-2070))
UKpop2000_2100[[74]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2073-2070)) / (2080-2070))
UKpop2000_2100[[75]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2074-2070)) / (2080-2070))
UKpop2000_2100[[76]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2075-2070)) / (2080-2070))
UKpop2000_2100[[77]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2076-2070)) / (2080-2070))
UKpop2000_2100[[78]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2077-2070)) / (2080-2070))
UKpop2000_2100[[79]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2078-2070)) / (2080-2070))
UKpop2000_2100[[80]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2079-2070)) / (2080-2070))
UKpop2000_2100[[81]] <- popM[[9]] #2080

years <- seq(as.Date("2000/01/01"), by = "year", length.out = 81)
UKpop2000_2100 <- setZ(UKpop2000_2100, years, "years")
names(UKpop2000_2100) <- years

#################################################
# Getting the proportion of people per grid
#################################################
# To get population weighted average, we need the fraction of the population
# that lives in each grid. So, we need to calculate D = pop in each grid / pop_TS

# UK
UKpop_TS2000_2100 <- c(cellStats(UKpop2000_2100, sum, na.rm=T)) # Total per layer

UKpopD2000_2100 <- brick(nrows=109, ncols=55, xmn=0, xmx=660000, ymn=-84000, ymx=1224000 , nl=81)

for (i in 1:nlayers(UKpop2000_2100)){
  UKpopD2000_2100[[i]] <- (UKpop2000_2100[[i]]  / UKpop_TS2000_2100[i] )
}   # UKpopD2000_2100 is a RasterBrick with the proportion of people living in each grid.

# Population by regions - To calculate regional exposures
# Channel Islands
Cha_pop2000_2100 <- mask(UKpop2000_2100, Cha_borders) %>% crop(Cha_borders) #NAs (due to size?)

# England
Eng_pop2000_2100 <- mask(UKpop2000_2100, Eng_borders) %>% crop(Eng_borders)
Eng_pop_TS2000_2100 <- c(cellStats(Eng_pop2000_2100, sum, na.rm=T))
Eng_popD2000_2100 <- brick(nrows=55, ncols=48, xmn=84000, xmx=660000, ymn=0, ymx=660000, nl=81)
for (i in 1:nlayers(Eng_pop2000_2100)){
  Eng_popD2000_2100[[i]] <- (Eng_pop2000_2100[[i]]  / Eng_pop_TS2000_2100[i] )
}

# Isle of Man
Isl_pop2000_2100 <- mask(UKpop2000_2100, Isl_borders) %>% crop(Isl_borders)
Isl_pop_TS2000_2100 <- c(cellStats(Isl_pop2000_2100, sum, na.rm=T))
Isl_popD2000_2100 <- brick(nrows=3, ncols=3, xmn=216000, xmx=252000, ymn=468000, ymx=504000, nl=81)
for (i in 1:nlayers(Isl_pop2000_2100)){
  Isl_popD2000_2100[[i]] <- (Isl_pop2000_2100[[i]]  / Isl_pop_TS2000_2100[i] )
}

# Northen Ireland
NIr_pop2000_2100 <- mask(UKpop2000_2100, NIr_borders) %>% crop(NIr_borders)
NIr_pop_TS2000_2100 <- c(cellStats(NIr_pop2000_2100, sum, na.rm=T))
NIr_popD2000_2100 <- brick(nrows=12, ncols=15, xmn=0, xmx=180000, ymn=468000, ymx=612000, nl=81)
for (i in 1:nlayers(NIr_pop2000_2100)){
  NIr_popD2000_2100[[i]] <- (NIr_pop2000_2100[[i]]  / NIr_pop_TS2000_2100[i] )
}

# Scotland
Sco_pop2000_2100 <- mask(UKpop2000_2100, Sco_borders) %>% crop(Sco_borders)
Sco_pop_TS2000_2100 <- c(cellStats(Sco_pop2000_2100, sum, na.rm=T))
Sco_popD2000_2100 <- brick(nrows=58, ncols=39, xmn=0, xmx=468000, ymn=528000, ymx=1224000, nl=81)
for (i in 1:nlayers(Sco_pop2000_2100)){
  Sco_popD2000_2100[[i]] <- (Sco_pop2000_2100[[i]]  / Sco_pop_TS2000_2100[i] )
}

# Wales
Wal_pop2000_2100 <- mask(UKpop2000_2100, Wal_borders) %>% crop(Wal_borders)
Wal_pop_TS2000_2100 <- c(cellStats(Wal_pop2000_2100, sum, na.rm=T))
Wal_popD2000_2100 <- brick(nrows=19, ncols=17, xmn=156000, xmx=360000, ymn=168000, ymx=396000, nl=81)
for (i in 1:nlayers(Wal_pop2000_2100)){
  Wal_popD2000_2100[[i]] <- (Wal_pop2000_2100[[i]]  / Wal_pop_TS2000_2100[i] )
}

###############################################################################
#   TEMPERATURE PROJECTIONS
###############################################################################

tasmin.nc <- nc_open("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmin_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc")
print(tasmin.nc)
names(tasmin.nc$var) #"tasmin"
tasmin <- brick("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmin_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc")
tasmin    # 1200 layers = 100 years

tasmax.nc <- nc_open("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmax_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc")
print(tasmax.nc)
names(tasmax.nc$var) #"tasmax"
tasmax <- brick("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmax_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc")

tas.nc <- nc_open("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tas_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc")
print(tas.nc)
names(tas.nc$var) #"tasmin"
tas <- brick("/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tas_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc")

#################################################
# Masking and dates manipulations
#################################################

# Masking (M) and cropping some grids
tasminM <- mask(tasmin, uk_borders) %>% crop(uk_borders)
tasmaxM <- mask(tasmax, uk_borders) %>% crop(uk_borders)
tasM <- mask(tas, uk_borders) %>% crop(uk_borders)

# Standardized layers' dates - From .nc to rasterbrick there are some problems with layers' names.
head(names(tasminM)) # "X1980.10.20" "X1980.11.19" "X1980.12.19" "X1981.01.18" "X1981.02.17" "X1981.03.19"
tail(names(tasminM)) # "X2078.11.15" "X2078.12.15" "X2079.01.14" "X2079.02.13" "X2079.03.15" "X2079.04.14"

time_layers <- seq(as.Date("1980/12/01"), as.Date("2080/11/30"), by = "month")

tasminM <- setZ(tasminM, time_layers, "months")
names(tasminM) <- time_layers

tasmaxM <- setZ(tasmaxM, time_layers, "months")
names(tasmaxM) <- time_layers

tasM <- setZ(tasM, time_layers, "months")
names(tasM) <- time_layers

#################################################
# Anomaly calculations
#################################################

# First, we need to calculate averages by month to get "historical" baseline - 1980 Dec (nl= 1) to 2000 Nov (nl= 240)
# We drop the layers we don't need (241:1200)
tasmin1980_2000 <- dropLayer(tasminM, c(241:1200))
tasmax1980_2000 <- dropLayer(tasmaxM, c(241:1200))
tas1980_2000 <- dropLayer(tasM, c(241:1200))

month_layers <- seq(as.Date("2000/12/1"), by = "month", length.out = 12)

# Using zApply, we have monthly means (of 20 Jans, 20 Febs...20 Decs). It stars from Dec-Nov
tasminSA1980_2000  <-  zApply(tasmin1980_2000, by=month, fun= mean, name = "months")
tasminSA1980_2000  <- setZ(tasminSA1980_2000, month_layers, "months")
names(tasminSA1980_2000) <- month_layers

tasmaxSA1980_2000  <-  zApply(tasmax1980_2000, by=month, fun= mean, name = "months")
tasmaxSA1980_2000 <- setZ(tasmaxSA1980_2000, month_layers, "months")
names(tasmaxSA1980_2000) <- month_layers

tasSA1980_2000  <-  zApply(tas1980_2000, by=month, fun= mean, name = "months")
tasSA1980_2000  <- setZ(tasSA1980_2000, month_layers, "months")
names(tasSA1980_2000) <- month_layers

# For current temperature: We're using from 2000 onward (Dec 1999 (nl= 229))
# We drop layers we do not need (Dec 1980 to Nov 1999)
tasmin2000_2080 <- dropLayer(tasminM, c(1:228))
tasmax2000_2080 <- dropLayer(tasmaxM, c(1:228))
tas2000_2080 <- dropLayer(tasM, c(1:228))

# Now, we need to subtract current temperature minus historical temperature by month
Dec_layers <- seq(as.Date("1999/12/01"), as.Date("2080/11/30"), by = "year")

TasMinAnom2000_2080 <-lapply(1:12, function(i) {
  m <- formatC(c(12,1:11), width = 2, flag= "0")[i]
  TasMinAnom <- (subset(tasmin2000_2080, which(substr(getZ(tasmin2000_2080),6,7) %in% c(m)))) - tasminSA1980_2000[[i]]
  if(m=="12") {Dec_layers <- as.Date(sapply(1999:2079, paste,m,"01",sep= "/"))} else {Dec_layers <- as.Date(sapply(2000:2080, paste,m,"01",sep= "/"))}
  names(TasMinAnom) <- Dec_layers
  return(TasMinAnom)
})

TasMinAnom2000_2080 <- stack(TasMinAnom2000_2080)

TasMaxAnom2000_2080 <-lapply(1:12, function(i) {
  m <- formatC(c(12,1:11), width = 2, flag= "0")[i]
  TasMaxAnom <- (subset(tasmax2000_2080, which(substr(getZ(tasmax2000_2080),6,7) %in% c(m)))) - tasmaxSA1980_2000[[i]]
  if(m=="12") {Dec_layers <- as.Date(sapply(1999:2079, paste,m,"01",sep= "/"))} else {Dec_layers <- as.Date(sapply(2000:2080, paste,m,"01",sep= "/"))}
  names(TasMaxAnom) <- Dec_layers
  return(TasMaxAnom)
})

TasMaxAnom2000_2080 <- stack(TasMaxAnom2000_2080)

TasAnom2000_2080 <-lapply(1:12, function(i) {
  m <- formatC(c(12,1:11), width = 2, flag= "0")[i]
  TasAnom <- (subset(tas2000_2080, which(substr(getZ(tas2000_2080),6,7) %in% c(m)))) - tasSA1980_2000[[i]]
  if(m=="12") {Dec_layers <- as.Date(sapply(1999:2079, paste,m,"01",sep= "/"))} else {Dec_layers <- as.Date(sapply(2000:2080, paste,m,"01",sep= "/"))}
  names(TasAnom) <- Dec_layers
  return(TasAnom)
})

TasAnom2000_2080 <- stack(TasAnom2000_2080)

Dec_layers <- seq(as.Date("1999/12/01"), as.Date("2080/11/30"), by = "year")
Jan_layers <- seq(as.Date("2000/01/01"), as.Date("2080/11/30"), by = "year")
Feb_layers <- seq(as.Date("2000/02/01"), as.Date("2080/11/30"), by = "year")
Mar_layers <- seq(as.Date("2000/03/01"), as.Date("2080/11/30"), by = "year")
Apr_layers <- seq(as.Date("2000/04/01"), as.Date("2080/11/30"), by = "year")
May_layers <- seq(as.Date("2000/05/01"), as.Date("2080/11/30"), by = "year")
Jun_layers <- seq(as.Date("2000/06/01"), as.Date("2080/11/30"), by = "year")
Jul_layers <- seq(as.Date("2000/07/01"), as.Date("2080/11/30"), by = "year")
Aug_layers <- seq(as.Date("2000/08/01"), as.Date("2080/11/30"), by = "year")
Sep_layers <- seq(as.Date("2000/09/01"), as.Date("2080/11/30"), by = "year")
Oct_layers <- seq(as.Date("2000/10/01"), as.Date("2080/11/30"), by = "year")
Nov_layers <- seq(as.Date("2000/11/01"), as.Date("2080/11/30"), by = "year")

Anom2000_2080_layers <- c(Dec_layers, Jan_layers, Feb_layers, Mar_layers, Apr_layers, May_layers,
                          Jun_layers, Jul_layers, Aug_layers, Sep_layers, Oct_layers, Nov_layers)

TasMinAnom2000_2080 <- setZ(TasMinAnom2000_2080 , Anom2000_2080_layers, name= "Date")
TasMaxAnom2000_2080 <- setZ(TasMaxAnom2000_2080, Anom2000_2080_layers, name= "Date")
TasAnom2000_2080 <- setZ(TasAnom2000_2080, Anom2000_2080_layers, name= "Date")

# Sorting raster layers by date
TasMinAnom2000_2080 <- TasMinAnom2000_2080[[order(getZ(TasMinAnom2000_2080))]]
TasMaxAnom2000_2080 <- TasMaxAnom2000_2080[[order(getZ(TasMaxAnom2000_2080))]]
TasAnom2000_2080 <- TasAnom2000_2080[[order(getZ(TasAnom2000_2080))]]

#################################################
# Area-weighted Average Monthly T Anomalies from 2000-2080
#################################################
UK_AWTasMinAnom2000_2080 <- c(cellStats(TasMinAnom2000_2080, mean, na.rm=T))
UK_AWTasMaxAnom2000_2080 <- c(cellStats(TasMaxAnom2000_2080, mean, na.rm=T))
UK_AWTasAnom2000_2080 <- c(cellStats(TasAnom2000_2080, mean, na.rm=T))

# England
Eng_TasMinAnom2000_2080  <- mask(TasMinAnom2000_2080, Eng_borders) %>% crop(Eng_borders)
Eng_TasMaxAnom2000_2080  <- mask(TasMaxAnom2000_2080, Eng_borders) %>% crop(Eng_borders)
Eng_TasAnom2000_2080  <- mask(TasAnom2000_2080, Eng_borders) %>% crop(Eng_borders)

Eng_AWTasMinAnom2000_2080 <- c(cellStats(Eng_TasMinAnom2000_2080, mean, na.rm=T))
Eng_AWTasMaxAnom2000_2080 <- c(cellStats(Eng_TasMaxAnom2000_2080, mean, na.rm=T))
Eng_AWTasAnom2000_2080 <- c(cellStats(Eng_TasAnom2000_2080, mean, na.rm=T))

# Isle of Man
Isl_TasMinAnom2000_2080  <- mask(TasMinAnom2000_2080, Isl_borders) %>% crop(Isl_borders)
Isl_TasMaxAnom2000_2080  <- mask(TasMaxAnom2000_2080, Isl_borders) %>% crop(Isl_borders)
Isl_TasAnom2000_2080  <- mask(TasAnom2000_2080, Isl_borders) %>% crop(Isl_borders)

Isl_AWTasMinAnom2000_2080 <- c(cellStats(Isl_TasMinAnom2000_2080, mean, na.rm=T))
Isl_AWTasMaxAnom2000_2080 <- c(cellStats(Isl_TasMaxAnom2000_2080, mean, na.rm=T))
Isl_AWTasAnom2000_2080 <- c(cellStats(Isl_TasAnom2000_2080, mean, na.rm=T))

# Northen Ireland
NIr_TasMinAnom2000_2080  <- mask(TasMinAnom2000_2080, NIr_borders) %>% crop(NIr_borders)
NIr_TasMaxAnom2000_2080  <- mask(TasMaxAnom2000_2080, NIr_borders) %>% crop(NIr_borders)
NIr_TasAnom2000_2080  <- mask(TasAnom2000_2080, NIr_borders) %>% crop(NIr_borders)

NIr_AWTasMinAnom2000_2080 <- c(cellStats(NIr_TasMinAnom2000_2080, mean, na.rm=T))
NIr_AWTasMaxAnom2000_2080 <- c(cellStats(NIr_TasMaxAnom2000_2080, mean, na.rm=T))
NIr_AWTasAnom2000_2080 <- c(cellStats(NIr_TasAnom2000_2080, mean, na.rm=T))

# Scotland
Sco_TasMinAnom2000_2080  <- mask(TasMinAnom2000_2080, Sco_borders) %>% crop(Sco_borders)
Sco_TasMaxAnom2000_2080  <- mask(TasMaxAnom2000_2080, Sco_borders) %>% crop(Sco_borders)
Sco_TasAnom2000_2080  <- mask(TasAnom2000_2080, Sco_borders) %>% crop(Sco_borders)

Sco_AWTasMinAnom2000_2080 <- c(cellStats(Sco_TasMinAnom2000_2080, mean, na.rm=T))
Sco_AWTasMaxAnom2000_2080 <- c(cellStats(Sco_TasMaxAnom2000_2080, mean, na.rm=T))
Sco_AWTasAnom2000_2080 <- c(cellStats(Sco_TasAnom2000_2080, mean, na.rm=T))

# Wales
Wal_TasMinAnom2000_2080  <- mask(TasMinAnom2000_2080, Wal_borders) %>% crop(Wal_borders)
Wal_TasMaxAnom2000_2080  <- mask(TasMaxAnom2000_2080, Wal_borders) %>% crop(Wal_borders)
Wal_TasAnom2000_2080  <- mask(TasAnom2000_2080, Wal_borders) %>% crop(Wal_borders)

Wal_AWTasMinAnom2000_2080 <- c(cellStats(Wal_TasMinAnom2000_2080, mean, na.rm=T))
Wal_AWTasMaxAnom2000_2080 <- c(cellStats(Wal_TasMaxAnom2000_2080, mean, na.rm=T))
Wal_AWTasAnom2000_2080 <- c(cellStats(Wal_TasAnom2000_2080, mean, na.rm=T))

#################################################
# Population-weighted Average Monthly T Anomalies
#################################################

# UK
UK_PWTasMinAnom2000_2080 <- brick(extend(UKpopD2000_2100, UKpopD2000_2100))
UK_PWTasMaxAnom2000_2080 <- brick(extend(UKpopD2000_2100, UKpopD2000_2100))
UK_PWTasAnom2000_2080 <- brick(extend(UKpopD2000_2100, UKpopD2000_2100))
for (i in 1:nlayers(UKpopD2000_2100)){
  for (j in 1:12) {
    UK_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- TasMinAnom2000_2080[[(12*(i-1))+j]] * UKpopD2000_2100[[i]]
    UK_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- TasMaxAnom2000_2080[[(12*(i-1))+j]] * UKpopD2000_2100[[i]]
    UK_PWTasAnom2000_2080[[(12*(i-1))+j]] <- TasAnom2000_2080[[(12*(i-1))+j]] * UKpopD2000_2100[[i]]
  }
}

UKv_PWTasMinAnom2000_2080 <- c(cellStats(UK_PWTasMinAnom2000_2080, sum, na.rm=T))
UKv_PWTasMaxAnom2000_2080 <- c(cellStats(UK_PWTasMaxAnom2000_2080, sum, na.rm=T))
UKv_PWTasAnom2000_2080 <- c(cellStats(UK_PWTasAnom2000_2080, sum, na.rm=T))

# Eng
Eng_PWTasMinAnom2000_2080 <- brick(extend(Eng_popD2000_2100, Eng_popD2000_2100))
Eng_PWTasMaxAnom2000_2080 <- brick(extend(Eng_popD2000_2100, Eng_popD2000_2100))
Eng_PWTasAnom2000_2080 <- brick(extend(Eng_popD2000_2100, Eng_popD2000_2100))
for (i in 1:nlayers(Eng_popD2000_2100)){
  for (j in 1:12) {
    Eng_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- Eng_TasMinAnom2000_2080[[(12*(i-1))+j]] * Eng_popD2000_2100[[i]]
    Eng_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- Eng_TasMaxAnom2000_2080[[(12*(i-1))+j]] * Eng_popD2000_2100[[i]]
    Eng_PWTasAnom2000_2080[[(12*(i-1))+j]] <- Eng_TasAnom2000_2080[[(12*(i-1))+j]] * Eng_popD2000_2100[[i]]
  }
}

Engv_PWTasMinAnom2000_2080 <- c(cellStats(Eng_PWTasMinAnom2000_2080, sum, na.rm=T))
Engv_PWTasMaxAnom2000_2080 <- c(cellStats(Eng_PWTasMaxAnom2000_2080, sum, na.rm=T))
Engv_PWTasAnom2000_2080 <- c(cellStats(Eng_PWTasAnom2000_2080, sum, na.rm=T))

# NIr
NIr_PWTasMinAnom2000_2080 <- brick(extend(NIr_popD2000_2100, NIr_popD2000_2100))
NIr_PWTasMaxAnom2000_2080 <- brick(extend(NIr_popD2000_2100, NIr_popD2000_2100))
NIr_PWTasAnom2000_2080 <- brick(extend(NIr_popD2000_2100, NIr_popD2000_2100))
for (i in 1:nlayers(NIr_popD2000_2100)){
  for (j in 1:12) {
    NIr_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- NIr_TasMinAnom2000_2080[[(12*(i-1))+j]] * NIr_popD2000_2100[[i]]
    NIr_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- NIr_TasMaxAnom2000_2080[[(12*(i-1))+j]] * NIr_popD2000_2100[[i]]
    NIr_PWTasAnom2000_2080[[(12*(i-1))+j]] <- NIr_TasAnom2000_2080[[(12*(i-1))+j]] * NIr_popD2000_2100[[i]]
  }
}

NIrv_PWTasMinAnom2000_2080 <- c(cellStats(NIr_PWTasMinAnom2000_2080, sum, na.rm=T))
NIrv_PWTasMaxAnom2000_2080 <- c(cellStats(NIr_PWTasMaxAnom2000_2080, sum, na.rm=T))
NIrv_PWTasAnom2000_2080 <- c(cellStats(NIr_PWTasAnom2000_2080, sum, na.rm=T))

# Sco
Sco_PWTasMinAnom2000_2080 <- brick(extend(Sco_popD2000_2100, Sco_popD2000_2100))
Sco_PWTasMaxAnom2000_2080 <- brick(extend(Sco_popD2000_2100, Sco_popD2000_2100))
Sco_PWTasAnom2000_2080 <- brick(extend(Sco_popD2000_2100, Sco_popD2000_2100))
for (i in 1:nlayers(Sco_popD2000_2100)){
  for (j in 1:12) {
    Sco_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- Sco_TasMinAnom2000_2080[[(12*(i-1))+j]] * Sco_popD2000_2100[[i]]
    Sco_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- Sco_TasMaxAnom2000_2080[[(12*(i-1))+j]] * Sco_popD2000_2100[[i]]
    Sco_PWTasAnom2000_2080[[(12*(i-1))+j]] <- Sco_TasAnom2000_2080[[(12*(i-1))+j]] * Sco_popD2000_2100[[i]]
  }
}

Scov_PWTasMinAnom2000_2080 <- c(cellStats(Sco_PWTasMinAnom2000_2080, sum, na.rm=T))
Scov_PWTasMaxAnom2000_2080 <- c(cellStats(Sco_PWTasMaxAnom2000_2080, sum, na.rm=T))
Scov_PWTasAnom2000_2080 <- c(cellStats(Sco_PWTasAnom2000_2080, sum, na.rm=T))

# Wal
Wal_PWTasMinAnom2000_2080 <- brick(extend(Wal_popD2000_2100, Wal_popD2000_2100))
Wal_PWTasMaxAnom2000_2080 <- brick(extend(Wal_popD2000_2100, Wal_popD2000_2100))
Wal_PWTasAnom2000_2080 <- brick(extend(Wal_popD2000_2100, Wal_popD2000_2100))
for (i in 1:nlayers(Wal_popD2000_2100)){
  for (j in 1:12) {
    Wal_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- Wal_TasMinAnom2000_2080[[(12*(i-1))+j]] * Wal_popD2000_2100[[i]]
    Wal_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- Wal_TasMaxAnom2000_2080[[(12*(i-1))+j]] * Wal_popD2000_2100[[i]]
    Wal_PWTasAnom2000_2080[[(12*(i-1))+j]] <- Wal_TasAnom2000_2080[[(12*(i-1))+j]] * Wal_popD2000_2100[[i]]
  }
}

Walv_PWTasMinAnom2000_2080 <- c(cellStats(Wal_PWTasMinAnom2000_2080, sum, na.rm=T))
Walv_PWTasMaxAnom2000_2080 <- c(cellStats(Wal_PWTasMaxAnom2000_2080, sum, na.rm=T))
Walv_PWTasAnom2000_2080 <- c(cellStats(Wal_PWTasAnom2000_2080, sum, na.rm=T))

write.csv(as.data.frame(cbind(UK_AWTasMinAnom2000_2080, UK_AWTasMaxAnom2000_2080, UK_AWTasAnom2000_2080,
                              Eng_AWTasMinAnom2000_2080, Eng_AWTasMaxAnom2000_2080, Eng_AWTasAnom2000_2080,
                              NIr_AWTasMinAnom2000_2080, NIr_AWTasMaxAnom2000_2080, NIr_AWTasAnom2000_2080,
                              Sco_AWTasMinAnom2000_2080, Sco_AWTasMaxAnom2000_2080, Sco_AWTasAnom2000_2080,
                              Wal_AWTasMinAnom2000_2080, Wal_AWTasMaxAnom2000_2080, Wal_AWTasAnom2000_2080,
                              UKv_PWTasMinAnom2000_2080, UKv_PWTasMaxAnom2000_2080, UKv_PWTasAnom2000_2080,
                              Engv_PWTasMinAnom2000_2080, Engv_PWTasMaxAnom2000_2080, Engv_PWTasAnom2000_2080,
                              NIrv_PWTasMinAnom2000_2080, NIrv_PWTasMaxAnom2000_2080, NIrv_PWTasAnom2000_2080,
                              Scov_PWTasMinAnom2000_2080, Scov_PWTasMaxAnom2000_2080, Scov_PWTasAnom2000_2080,
                              Walv_PWTasMinAnom2000_2080, Walv_PWTasMaxAnom2000_2080, Walv_PWTasAnom2000_2080)), "AW_PW_MonthlyTAnomalies2000_2080.csv")

###############################################################################
#   VISUALISATIONS
###############################################################################

#################################################
# Area-weighted Average Monthly T Anomalies from 2000-2080
#################################################

AW_PW_MonthlyTAnomalies2000_2080 <- read.csv("AW_PW_MonthlyTAnomalies2000_2080.csv")
AW_PW_MonthlyTAnomalies2000_2080$date <- as.Date(seq(as.Date("1999/12/01"), as.Date("2080/11/01"), by = "month"))

#TasMin
AW_PW_MonthlyTAnomalies2000_2080$S_UK_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
UK_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UK_AWTasMinAnom2000_2080, fill= S_UK_AWTasMinAnom2000_2080)) +
  geom_bar(stat = "identity", show.legend = FALSE) +
  #scale_x_date(date_breaks = "years", date_labels = "%Y") +
  scale_y_continuous(breaks = seq(-4, 10, 2)) +
  scale_fill_manual(values = c("#99000d", "#034e7b")) +
  labs(y = "Temperature anomaly (°C)", x = "",
       title= "Monthly Minimum Temperature anomaly (°C) in the UK 2000-2080", subtitle= "compared to 1980-2000 average",
       caption= "Data: UKCP18") +
  theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Eng_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Eng_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasMinAnom2000_2080, fill= S_Eng_AWTasMinAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Minimum Temperature anomaly (°C) in England 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_NIr_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
NIr_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIr_AWTasMinAnom2000_2080, fill= S_NIr_AWTasMinAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Minimum Temperature anomaly (°C) in the Northern Ireland 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Sco_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Sco_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Sco_AWTasMinAnom2000_2080, fill= S_Sco_AWTasMinAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Minimum Temperature anomaly (°C) in Scotland 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Wal_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Wal_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Wal_AWTasMinAnom2000_2080, fill= S_Wal_AWTasMinAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Minimum Temperature anomaly (°C) in Wales 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                theme_hc())

p1 <- ggarrange(UK_TasMin, ncol=1, nrow=1)
p2 <- ggarrange(Eng_TasMin, NIr_TasMin, Sco_TasMin, Wal_TasMin, ncol=2, nrow=2)
p3 <- ggarrange(p1, p2, ncol=1, nrow= 2)

#TasMax
AW_PW_MonthlyTAnomalies2000_2080$S_UK_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
UK_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UK_AWTasMaxAnom2000_2080, fill= S_UK_AWTasMaxAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Maximum Temperature anomaly (°C) in the UK 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Eng_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Eng_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasMaxAnom2000_2080, fill= S_Eng_AWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Maximum Temperature anomaly (°C) in England 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_NIr_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
NIr_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIr_AWTasMaxAnom2000_2080, fill= S_NIr_AWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Maximum Temperature anomaly (°C) in the Northern Ireland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Sco_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Sco_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Sco_AWTasMaxAnom2000_2080, fill= S_Sco_AWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Maximum Temperature anomaly (°C) in Scotland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Wal_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Wal_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Wal_AWTasMaxAnom2000_2080, fill= S_Wal_AWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Maximum Temperature anomaly (°C) in Wales 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

p4 <- ggarrange(UK_TasMax, ncol=1, nrow=1)
p5 <- ggarrange(Eng_TasMax, NIr_TasMax, Sco_TasMax, Wal_TasMax, ncol=2, nrow=2)
p6 <- ggarrange(p4, p5, ncol=1, nrow= 2)

#Tas
AW_PW_MonthlyTAnomalies2000_2080$S_UK_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
UK_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UK_AWTasAnom2000_2080, fill= S_UK_AWTasAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Mean Temperature anomaly (°C) in the UK 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Eng_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Eng_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasAnom2000_2080, fill= S_Eng_AWTasAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Mean Temperature anomaly (°C) in England 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_NIr_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
NIr_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIr_AWTasAnom2000_2080, fill= S_NIr_AWTasAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Mean Temperature anomaly (°C) in the Northern Ireland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Sco_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Sco_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Sco_AWTasAnom2000_2080, fill= S_Sco_AWTasAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Mean Temperature anomaly (°C) in Scotland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Wal_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Wal_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Wal_AWTasAnom2000_2080, fill= S_Wal_AWTasAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Mean Temperature anomaly (°C) in Wales 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

p7 <- ggarrange(UK_Tas, ncol=1, nrow=1)
p8 <- ggarrange(Eng_Tas, NIr_Tas, Sco_Tas, Wal_Tas, ncol=2, nrow=2)
p9 <- ggarrange(p7, p8, ncol=1, nrow= 2)

#################################################
# Population-weighted Average Monthly Anomalies
#################################################

#TasMin
AW_PW_MonthlyTAnomalies2000_2080$S_UK_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
UK_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UKv_PWTasMinAnom2000_2080, fill= S_UK_PWTasMinAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Population-weighted Minimum Temperature anomaly (°C) in the UK 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Eng_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Eng_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasMinAnom2000_2080, fill= S_Eng_PWTasMinAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Minimum Temperature anomaly (°C) in England 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_NIr_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
NIr_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIrv_PWTasMinAnom2000_2080, fill= S_NIr_PWTasMinAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Minimum Temperature anomaly (°C) in the Northern Ireland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Sco_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Sco_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Scov_PWTasMinAnom2000_2080, fill= S_Sco_PWTasMinAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Minimum Temperature anomaly (°C) in Scotland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Wal_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMinAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Wal_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Walv_PWTasMinAnom2000_2080, fill= S_Wal_PWTasMinAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Minimum Temperature anomaly (°C) in Wales 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

p10 <- ggarrange(UK_PWTasMin, ncol=1, nrow=1)
p11 <- ggarrange(Eng_PWTasMin, NIr_PWTasMin, Sco_PWTasMin, Wal_PWTasMin, ncol=2, nrow=2)
p12 <- ggarrange(p10, p11, ncol=1, nrow= 2)

#TasMax
AW_PW_MonthlyTAnomalies2000_2080$S_UK_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
UK_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UKv_PWTasMaxAnom2000_2080, fill= S_UK_PWTasMaxAnom2000_2080)) +
                geom_bar(stat = "identity", show.legend = FALSE) +
                #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                scale_y_continuous(breaks = seq(-4, 10, 2)) +
                scale_fill_manual(values = c("#99000d", "#034e7b")) +
                labs(y = "Temperature anomaly (°C)", x = "",
                     title= "Monthly Population-weighted Maximum Temperature anomaly (°C) in the UK 2000-2080", subtitle= "compared to 1980-2000 average",
                     caption= "Data: UKCP18") +
                theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Eng_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Eng_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Engv_PWTasMaxAnom2000_2080, fill= S_Eng_PWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 #scale_x_date(date_breaks = "years", date_labels = "%Y") +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Maximum Temperature anomaly (°C) in England 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_NIr_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
NIr_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIrv_PWTasMaxAnom2000_2080, fill= S_NIr_PWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Maximum Temperature anomaly (°C) in the Northern Ireland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Sco_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Sco_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Scov_PWTasMaxAnom2000_2080, fill= S_Sco_PWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Maximum Temperature anomaly (°C) in Scotland 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Wal_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMaxAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Wal_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Walv_PWTasMaxAnom2000_2080, fill= S_Wal_PWTasMaxAnom2000_2080)) +
                 geom_bar(stat = "identity", show.legend = FALSE) +
                 scale_y_continuous(breaks = seq(-4, 10, 2)) +
                 scale_fill_manual(values = c("#99000d", "#034e7b")) +
                 labs(y = "Temperature anomaly (°C)", x = "",
                      title= "Monthly Population-weighted Maximum Temperature anomaly (°C) in Wales 2000-2080", subtitle= "compared to 1980-2000 average",
                      caption= "Data: UKCP18") +
                 theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
                 theme_hc())

p13 <- ggarrange(UK_PWTasMax, ncol=1, nrow=1)
p14 <- ggarrange(Eng_PWTasMax, NIr_PWTasMax, Sco_PWTasMax, Wal_PWTasMax, ncol=2, nrow=2)
p15 <- ggarrange(p13, p14, ncol=1, nrow= 2)

#Tas
AW_PW_MonthlyTAnomalies2000_2080$S_UK_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
UK_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UKv_PWTasAnom2000_2080, fill= S_UK_PWTasAnom2000_2080)) +
             geom_bar(stat = "identity", show.legend = FALSE) +
             #scale_x_date(date_breaks = "years", date_labels = "%Y") +
             scale_y_continuous(breaks = seq(-4, 10, 2)) +
             scale_fill_manual(values = c("#99000d", "#034e7b")) +
             labs(y = "Temperature anomaly (°C)", x = "",
                  title= "Monthly Population-weighted Mean Temperature anomaly (°C) in the UK 2000-2080", subtitle= "compared to 1980-2000 average",
                  caption= "Data: UKCP18") +
             theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Eng_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Eng_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Engv_PWTasAnom2000_2080, fill= S_Eng_PWTasAnom2000_2080)) +
              geom_bar(stat = "identity", show.legend = FALSE) +
              #scale_x_date(date_breaks = "years", date_labels = "%Y") +
              scale_y_continuous(breaks = seq(-4, 10, 2)) +
              scale_fill_manual(values = c("#99000d", "#034e7b")) +
              labs(y = "Temperature anomaly (°C)", x = "",
                   title= "Monthly Population-weighted Mean Temperature anomaly (°C) in England 2000-2080", subtitle= "compared to 1980-2000 average",
                   caption= "Data: UKCP18") +
              theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
              theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_NIr_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
NIr_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIrv_PWTasAnom2000_2080, fill= S_NIr_PWTasAnom2000_2080)) +
              geom_bar(stat = "identity", show.legend = FALSE) +
              scale_y_continuous(breaks = seq(-4, 10, 2)) +
              scale_fill_manual(values = c("#99000d", "#034e7b")) +
              labs(y = "Temperature anomaly (°C)", x = "",
                   title= "Monthly Population-weighted Mean Temperature anomaly (°C) in the Northern Ireland 2000-2080", subtitle= "compared to 1980-2000 average",
                   caption= "Data: UKCP18") +
              theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
              theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Sco_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Sco_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Scov_PWTasAnom2000_2080, fill= S_Sco_PWTasAnom2000_2080)) +
              geom_bar(stat = "identity", show.legend = FALSE) +
              scale_y_continuous(breaks = seq(-4, 10, 2)) +
              scale_fill_manual(values = c("#99000d", "#034e7b")) +
              labs(y = "Temperature anomaly (°C)", x = "",
                   title= "Monthly Population-weighted Mean Temperature anomaly (°C) in Scotland 2000-2080", subtitle= "compared to 1980-2000 average",
                   caption= "Data: UKCP18") +
              theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
              theme_hc())

AW_PW_MonthlyTAnomalies2000_2080$S_Wal_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasAnom2000_2080 >0, "pos","neg") %>% factor(c("pos", "neg"))
Wal_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Walv_PWTasAnom2000_2080, fill= S_Wal_PWTasAnom2000_2080)) +
              geom_bar(stat = "identity", show.legend = FALSE) +
              scale_y_continuous(breaks = seq(-4, 10, 2)) +
              scale_fill_manual(values = c("#99000d", "#034e7b")) +
              labs(y = "Temperature anomaly (°C)", x = "",
                   title= "Monthly Population-weighted Mean Temperature anomaly (°C) in Wales 2000-2080", subtitle= "compared to 1980-2000 average",
                   caption= "Data: UKCP18") +
              theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +
              theme_hc())

p16 <- ggarrange(UK_PWTas, ncol=1, nrow=1)
p17 <- ggarrange(Eng_PWTas, NIr_PWTas, Sco_PWTas, Wal_PWTas, ncol=2, nrow=2)
p18 <- ggarrange(p16, p17, ncol=1, nrow= 2)

#################################################
# Time series plots for AW an PW
#################################################
data.frame(colnames(AW_PW_MonthlyTAnomalies2000_2080))

layout(matrix(c(1,1,2,3,4,5), 3, 2, byrow = TRUE))

AW_PW_MonthlyTAnomalies2000_2080$Year <- as.numeric(substr(AW_PW_MonthlyTAnomalies2000_2080$date,1,4))
AW_PW_MonthlyTAnomalies2000_2080$Month <- as.numeric(substr(AW_PW_MonthlyTAnomalies2000_2080$date,6,7))
AW_PW_MonthlyTAnomalies2000_2080$DecimalDate <- AW_PW_MonthlyTAnomalies2000_2080$Year + (AW_PW_MonthlyTAnomalies2000_2080$Month / 12) - 1/24

#TasMin
# UK
UK_TasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
UK_PWTasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(2,17)], type="l",
        xlab="Year", main= "Monthly Minimum Temperature anomaly (°C) in the UK 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_TasMin.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_PWTasMin.decomp$time.series[,2], col="red", lwd=3)
legend("bottomright", legend= c("Area Weighted", "Population Weighted"), lwd= 2, col=c("lightblue", "salmon"), bg= ("white"), horiz= F)

# England
Eng_TasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Eng_PWTasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(5,20)], type="l",
        xlab="Year", main= "Monthly Minimum Temperature anomaly (°C) in the England 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_TasMin.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_PWTasMin.decomp$time.series[,2], col="red", lwd=3)

# NIr
NIr_TasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
NIr_PWTasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(8,23)], type="l",
        xlab="Year", main= "Monthly Minimum Temperature anomaly (°C) in the N.I. 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_TasMin.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_PWTasMin.decomp$time.series[,2], col="red", lwd=3)

# Scotland
Sco_TasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Sco_PWTasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(11,26)], type="l",
        xlab="Year", main= "Monthly Minimum Temperature anomaly (°C) in the Scotland 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_TasMin.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_PWTasMin.decomp$time.series[,2], col="red", lwd=3)

# Wales
Wal_TasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Wal_PWTasMin.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(14,29)], type="l",
        xlab="Year", main= "Monthly Minimum Temperature anomaly (°C) in the Wales 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_TasMin.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_PWTasMin.decomp$time.series[,2], col="red", lwd=3)

#TasMax
# UK
UK_TasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
UK_PWTasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(3,18)], type="l",
        xlab="Year", main= "Monthly Maximum Temperature anomaly (°C) in the UK 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_TasMax.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_PWTasMax.decomp$time.series[,2], col="red", lwd=3)
legend("bottomright", legend= c("Area Weighted", "Population Weighted"), lwd= 2, col=c("lightblue", "salmon"), bg= ("white"), horiz= F)

# England
Eng_TasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Eng_PWTasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(6,21)], type="l",
        xlab="Year", main= "Monthly Maximum Temperature anomaly (°C) in the England 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_TasMax.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_PWTasMax.decomp$time.series[,2], col="red", lwd=3)

# NIr
NIr_TasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
NIr_PWTasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(9,24)], type="l",
        xlab="Year", main= "Monthly Maximum Temperature anomaly (°C) in the N.I. 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_TasMax.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_PWTasMax.decomp$time.series[,2], col="red", lwd=3)

# Scotland
Sco_TasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Sco_PWTasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(12,27)], type="l",
        xlab="Year", main= "Monthly Maximum Temperature anomaly (°C) in the Scotland 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_TasMax.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_PWTasMax.decomp$time.series[,2], col="red", lwd=3)

# Wales
Wal_TasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Wal_PWTasMax.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(15,30)], type="l",
        xlab="Year", main= "Monthly Maximum Temperature anomaly (°C) in the Wales 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_TasMax.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_PWTasMax.decomp$time.series[,2], col="red", lwd=3)

#Tas
# UK
UK_Tas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
UK_PWTas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(4,19)], type="l",
        xlab="Year", main= "Monthly Mean Temperature anomaly (°C) in the UK 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_Tas.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_PWTas.decomp$time.series[,2], col="red", lwd=3)
legend("bottomright", legend= c("Area Weighted", "Population Weighted"), lwd= 2, col=c("lightblue", "salmon"), bg= ("white"), horiz= F)

# England
Eng_Tas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Eng_PWTas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(7,22)], type="l",
        xlab="Year", main= "Monthly Mean Temperature anomaly (°C) in the England 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_Tas.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_PWTas.decomp$time.series[,2], col="red", lwd=3)

# NIr
NIr_Tas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
NIr_PWTas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(10,25)], type="l",
        xlab="Year", main= "Monthly MeanTemperature anomaly (°C) in the N.I. 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_Tas.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_PWTas.decomp$time.series[,2], col="red", lwd=3)

# Scotland
Sco_Tas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Sco_PWTas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(13,28)], type="l",
        xlab="Year", main= "Monthly Mean Temperature anomaly (°C) in the Scotland 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_Tas.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_PWTas.decomp$time.series[,2], col="red", lwd=3)

# Wales
Wal_Tas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
Wal_PWTas.decomp <-
  stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)),
      s.window=11, t.window=121)
matplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(16,31)], type="l",
        xlab="Year", main= "Monthly Mean Temperature anomaly (°C) in the Wales 2000-2080", ylab=expression(degree * "C"),
        col=c("lightblue", "salmon"), lwd=2, lty=1)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_Tas.decomp$time.series[,2], col="blue", lwd=3)
lines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_PWTas.decomp$time.series[,2], col="red", lwd=3)