library(s2dverification)


pslFull <-  Load(var = psl, exp = NULL, obs = list(list(path=fields)), 
                 paste0(1981:2010,'1201'), storefreq = 'monthly', leadtimemin = 1, leadtimemax = 3, 
                 output = 'lonlat', latmin = lat.min, latmax = lat.max, lonmin = lon.min, lonmax = lon.max, nprocs=availableCores())
seasonal<-Mean1Dim(pslFull$obs,4)
clim<-Mean1Dim(seasonal,3)

anom<-seasonal-InsertDim(clim,3,30)

eofs<-EOF(ano=drop(anom),lon=pslFull$lon,lat = pslFull$lat,neofs = 4)

x11()
PlotLayout(PlotEquiMap,c(2,3),var=eofs$EOFs,lat=pslFull$lat,lon=pslFull$lon,filled.continents=F)

psl_anom<-anom
  
regressionMaps<-function(anom,index){
  anom=psl_anom
  index=stand
  postime<-which(dim(anom)==length(index))
  lm_fun<-function(x,y){
    #if (is.na(mean(y))){
      lm(y~x)$coefficients[[2]]
    #}else{
     # NA
    #}
  }
  regress_map<-apply(anom,(1:length(dim(anom)))[-postime],lm_fun,x=index)
}

stand<-(eofs$PCs[,1]-mean(eofs$PCs[,1]))/sd(eofs$PCs[,1])
RM<-regressionMaps(anom=anom,index=stand)

x11()
PlotEquiMap(var=drop(RM),lon=pslFull$lon,lat=pslFull$lat,filled.continents = F)










