
# Creation:  4/2018
# Authors: Nicola Cortesi and Llorenç Lledo
#
# Aim: To visualize the first X modes of variability for a given spatial domain and period from a reanalysis or from a forecast system
#
# Assumption: it needs the regressionMaps() function
#
# Branch: teleconnections
#
# Example:
#
## Compute rotated PCs truncating the loadings to 30:
# test <- REOF(ano=anom, lat, lon, ntrunc=30)
#
## Visualize the first four rotated PCs:
# ProjEOF(anom, lat, lon, test$RPCs[,1:4])
#

ProjEOF <- function(ano, lat, lon, PCs){
    nlat <- length(lat)
    nlon <- length(lon)
    nPCs <- dim(PCs)[2]
    
    proj.cor <- proj.reg <- array(NA, c(nPCs, nlat, nlon))
    
    for(t in 1:nPCs) proj.cor[t,,] <- apply(ano, c(2,3), function(x) cor(x, PCs[,t], use = "na.or.complete"))
    for(t in 1:nPCs) {
        PCs.stand <- (PCs[,t] - mean(PCs[,t])) / sd(PCs[,t]) ## Standardize the PCs
        proj.reg[t,,] <- regressionMaps(anom=ano, index=PCs.stand)
    }
    
    brks.corr <- c(-1, -0.8, -0.6, -0.4, -0.2, 0,  0.2, 0.4, 0.6, 0.8, 1)
    cols.corr <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(brks.corr)-1)    # blue--red colors
    PlotLayout(PlotEquiMap, c(2,3), var=proj.cor, lat=lat, lon=lon, filled.continents=FALSE, brks=brks.corr, cols=cols.corr)
    
    invisible(list(proj.cor, proj.reg))
}
    


