
# Creation:  6/2016
# Author: Nicola Cortesi
# Aim: To compute the four Euro-Atlantic weather regimes from a reanalysis or from a forecast system
#
# I/O: input must be in a format compatible with Load(); 1 output .RData file is created in the 'workdir' folder.
#      You can also run this script from terminal with: Rscript ~/scripts/weather_regimes_maps.R
#
# Assumption:  its output are needed by the scripts weather_regimes_impact.R and  weather_regimes.R
#
# Branch: weather_regimes

rm(list=ls())
library(s2dverification)  # for the function Load()
library(abind)
library(reshape2) # after each update of s2dverification, it's better to remove and install this package again because sometimes it gets broken! 

SMP <- FALSE   # if TRUE, the script is assumed to run on the SMP Machine
if(SMP){
   source('/gpfs/projects/bsc32/bsc32842/Rfunctions.R')
   workdir <- "/gpfs/projects/bsc32/bsc32842/RESILIENCE"  # working dir where output files will be generated
} else {
   source('/home/Earth/ncortesi/scripts/Rfunctions.R')
   workdir <- "/scratch/Earth/ncortesi/RESILIENCE/Regimes"  # working dir where output files will be generated
}

# module load NCO # : load it from the terminal before running this script interactively in the SMP machine, if you didn't load it in the .bashrc

f6h <- TRUE  # set if suffix "_f6h" is present in the file name or not (set it always to TRUE except if rean = JRA55 and psl = "z500")

# available reanalysis for the geopotential (g500) or the geopotential height (z500 = g500/9.81) and for var data:
ERAint <- '/esnas/recon/ecmwf/erainterim/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
#ERAint <- '/esarchive/old-files/recon_ecmwf_erainterim/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
ERAint <- '/esnas/recon/ecmwf/erainterim/6hourly/$VAR_NAME$/$VAR_NAME$_$YEAR$$MONTH$.nc'   # subdaily data!!!!!
ERAint.name <- "ERA-Interim"

JRA55 <- '/esnas/recon/jma/jra55/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
JRA55.name <- "JRA-55"

NCEP <- '/esnas/recon/noaa/ncep-reanalysis/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
NCEP.name <- "NCEP"

rean <- ERAint #JRA55 #ERAint #NCEP  # choose one of the two above reanalysis from where to load the input psl data

# available forecast systems for the psl and var data:
#ECMWF_S4 <- list(path = paste0('/esnas/exp/ECMWF/seasonal/0001/s004/m001/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$START_DATE$.nc'))
#ECMWF_S4 <- '/esnas/exp/ECMWF/seasonal/0001/s004/m001/$STORE_FREQ$_mean/psl_f6h/psl_$START_DATE$.nc'
ECMWF_S4 <- '/esnas/exp/ecmwf/system4_m1/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$START_DATE$.nc'
ECMWF_S4.name <- "ECMWF-S4"
member.name <- "ensemble"   # name of the dimension with the ensemble members inside the netCDF files of S4

ECMWF_monthly <- '/esnas/exp/ECMWF/monthly/ensforhc/6hourly/$VAR_NAME$/2014$MONTH$$DAY$00/$VAR_NAME$_$START_DATE$00.nc'
ECMWF_monthly.name <- "ECMWF-Monthly"

# choose a forecast system:
forecast <- ECMWF_S4  

# put 'rean' to load pressure fields and var from reanalisis, or put 'forecast' to load them from forecast systems:
fields <- rean #forecast  

psl <- "sfcWind" # "psl" #"g500" "tas"                          # pressure variable to use from the chosen reanalysis
psl.name <- "10-m Wind Speed" # "Surface Temperature" #"SLP" # "Z500"                     # the name to show in the maps

year.start <- 1981 #1979 #1981 #1982 #1981 #1994 #1979 #1981
year.end <- 2010 #2017 #2017 #2015

LOESS <- TRUE              # To apply the LOESS filter or not to the climatology
running.cluster <- FALSE   # add to the clustering also the daily SLP data of the two closer months to the month to use (only for monthly analysis)
running.15 <- FALSE        # add to the clustering also the daily SLP data of the 15 days of the two closer months (only for monthly analysis). You cannot set to TRUE both
                                        # this variable and 'running.cluster' above
lat.weighting <- TRUE      # set it to true to weight psl data on latitude before applying the cluster analysis
subdaily <- FALSE           # id TRUE, compute the clustering using 6-hourly data instead of daily data, to be more robust (only for reanalysis with 6-hourly data avail.)

sequences <-FALSE          # set it to TRUE if you want to select only days beloning to sequences of at least 5 consecutive days belonging to the same regime.
PCA <- FALSE                # set it to TRUE if you want to apply the PCA before the k-means cluster analysis, FALSE otherwise
variance.explained <- 0.8  # the user can set here the minimum % of variance explained by the PCs (typically 0.8 which is equal to 80%)

# Coordinates of the box enclosing the study region (the Northern Atlantic in this case):
lat.max <- 81 #81 #80 #70
lat.min <- 27 #30 #20 #30
lon.max <- 45 #36 #30 #40 
lon.min <- 274.5 #274.5 #270 #280 # put a positive number here because the geopotential has only positive vaues of longitud!
# Kiev: lat 50 lon 31

# Only for reanalysis:
WR.period <- 1 # 13:16 #1:12 #13:16  # 1-12: Jan-Dec; 13-16: Winter-Spring-Summer-Autumn  [bypassed by the optional argument of the script]

# Only for Seasonal forecasts:

leadM <- 0                                       # select only the data of one lead month:  [bypassed by the optional arguments of the script]
n.members <- 15                                  # number of members of the forecast system to load
n.leadtimes <- 216                               # number of leadtimes of the forecast system to load
missing.forecasts <- FALSE # set it to TRUE if there can be missing hindcasts files in the forecast psl data, so it will load only the available years and deals with NA
res <- 0.75                # set the resolution you want to interpolate the seasonal psl and var data when loading it (i.e: set to 0.75 to use the same res of ERA-Interim)
                           # interpolation method is BILINEAR.

# Only for Monthly forecasts:
#leadtime <- 1:7 #5:11 #1                        # if fields=forecast, set the forecast time (in days) you want to compute the weather regimes.
#startdate.shift <- 1                            # if leadtime=5:11, it's better to shift all startdates of the season 1 week in the past, to fit the exact season of obs.data
                                                 # if leadtime=12:18, it's better to shift all startdates of the season 2 weeks in the past, and so on.
#forecast.year <- year.end+1                     # if fields=forecast, set the forecast year (it is usually the year after year.end)
#mes=1                                           # if fields=forecast, set the month of the first startdate of the forecast year
#day=2                                           # if fields=forecast, set the day of the first startdate of the forecast year

#############################################################################################################################
rean.name <- unname(ifelse(rean == ERAint, ERAint.name, ifelse(rean == JRA55, JRA55.name, NCEP.name)))
forecast.name <- unname(ifelse(forecast == ECMWF_S4, ECMWF_S4.name, ECMWF_monthly.name))
fields.name <- unname(ifelse(fields == rean, rean.name, forecast.name))
n.years <- year.end - year.start + 1

if(running.cluster && running.15) stop("both 'running.cluster' and 'running.15' cannot be TRUE simultaneously")

if(!f6h) { pos <- regexpr("_f6h", fields); my.string <- strsplit(fields, "_f6h") ; fields <- paste0(my.string[[1]][1],my.string[[1]][2]) } # remove _f6h from filename

# in case the script is run with one argument, it is assumed a reanalysis is being used and the argument becomes the month we want to perform the clustering;
# in case the script is run with two arguments, it is assumed a forecast is used and the first argument represents the startmonth and the second one the leadmonth.
# in case the script is run with no arguments, the values of the variables inside the script are used:
script.arg <- as.integer(commandArgs(TRUE))

if(length(script.arg) == 0){
   start.month <- startM
   #WR.period <- start.month
   if(fields.name == forecast.name) lead.month <- leadM
}

# in case the script is run with 1 argument, it is assumed you are using a reanalysis:
if(length(script.arg) == 1){
   fields <- rean
   fields.name <- rean.name
   WR.period <-  script.arg[1]      
}

if(length(script.arg) >= 2){
   fields <- forecast
   fields.name <- forecast.name
   start.month <- script.arg[1]                 
   lead.month <- script.arg[2]
   WR.period <- start.month
}

if(length(script.arg) == 3){ # in this case, we are running the script in the SMP machine and we need to override the variables below:
   source('/gpfs/projects/bsc32/bsc32842/Rfunctions.R') # for the calendar function
   workdir <- "/gpfs/projects/bsc32/bsc32842/RESILIENCE"  # working dir
}

if(length(script.arg) >= 2) {lead.comment <- paste0("Lead month: ", lead.month)} else {lead.comment <- ""}
cat(paste0("Field: ", fields.name, " Period: ", WR.period, " ", lead.comment, "\n"))

if(lat.min >= lat.max) stop("lat.min cannot be greater than lat.max")

#days.period <- n.days.period <- period.length <- list()
#for (pp in 1:17){
#    days.period[[pp]] <- NA
#    for(y in year.start:year.end) days.period[[pp]] <- c(days.period[[pp]], n.days.in.a.future.year(year.start, y) + pos.period(y,pp))
#    days.period[[pp]] <- days.period[[pp]][-1] # remove the NA at the begin that was introduced only to be able to execute the above command
#    # number of days belonging to that period from year.start to year.end:
#    n.days.period[[pp]] <- length(days.period[[pp]])
#    # Number of days belonging to that period in a single year: 
#    period.length[[pp]] <- n.days.in.a.period(pp,1999) #+ ifelse(period==13 | period==2, 1, 0)  # using year 1999 introduce a small error in winter season length because of #bisestile years
#}

# Create a regular lat/lon grid to interpolate the data to the chosen res: (Notice that the regular grid is always centered at lat=0 and lon=0!)
n.lon.grid <- 360/res
n.lat.grid <- (180/res)+1
my.grid <- paste0('r',n.lon.grid,'x',n.lat.grid)
#domain<-list()
#domain$lon <- seq(0,359.999999999,res) 
#domain$lat <- c(rev(seq(0,90,res)),seq(res[1],-90,-res))

cat("Loading lat/lon. Please wait...\n")
# load only 1 day of pressure data to detect the minimum and maximum lat and lon values which identify only the North Atlantic area:
if(fields.name == rean.name) domain <- Load(var = psl, exp = NULL, obs = list(list(path=fields)), paste0(year.start,'0101'), storefreq = 'daily', leadtimemax = 1, output = 'lonlat', nprocs=1)

### Real test:
### lat <- 
### domain <- Load(var = "psl", exp = list(list(path="/esnas/exp/ecmwf/system4_m1/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$START_DATE$.nc")), obs=NULL, sdates=paste0(1982:2011,'0101'), storefreq = 'daily', leadtimemax=n.leadtimes, nmember=n.members, output = 'lonlat', latmin = lat[chunk], latmax = lat[chunk+2], nprocs=1)

### if (fields.name="pippo"){
    
# in the case of S4, we also interpolate it to the same resolution of the reanalysis:
# (notice that if the S4 grid has the same grid of the chosen grid (typically ERA-Interim), Load() leaves the S4 grid unchanged)

# for Paco (no interpolation):
if(fields.name == ECMWF_S4.name) domain <- Load(var = psl, exp = list(list(path=fields)), obs=NULL, sdates=paste0(year.start,'0101'), storefreq = 'daily', dimnames=list(member=member.name), leadtimemax=1, nmember=1, output = 'lonlat', nprocs=1)

n.lon <- length(domain$lon)
n.lat <- length(domain$lat)

pos.lat.max <- which(lat.max - round(domain$lat,4) >= 0)[1]           # select the first latitude of the domain below the maximum latitude
pos.lat.min <- tail(which(round(domain$lat,4) - lat.min >= 0),1)      # select the last latitude of the domain over the minumum latitude
pos.lon.max <- tail(which(lon.max - round(domain$lon,4) >= 0),1)
pos.lon.min <- which(round(domain$lon,4) - lon.min >= 0)[1]

pos.lat <- if(pos.lat.min < pos.lat.max) {pos.lat.min:pos.lat.max} else {pos.lat.max:pos.lat.min}
pos.lon <- c(1:pos.lon.max,pos.lon.min:length(domain$lon)) # beware that it only consider the case where the study area cross the meridian of Greenwhich!
n.pos.lat <- length(pos.lat)
n.pos.lon <- length(pos.lon)

lat <- domain$lat[pos.lat] # lat values of chosen area only (it is smaller than the whole spatial domain loaded by the data)
#if (lat[2] < lat[1]) lat <- rev(lat) # reverse lat values if they are in decreasing order
lon <- domain$lon[pos.lon] # lon values of chosen area only

#lat.min.area <- domain$lat[pos.lat.min] # min and max lat/lon of the chosen area only (same as lat.max, but its values correspond to actual values in the lat vector)
#lat.max.area <- domain$lat[pos.lat.max]
#lon.min.area <- domain$lon[pos.lon.min]
#lon.max.area <- domain$lon[pos.lon.max]

#rm(domain




# Load psl data (interpolating it to the same reanalysis grid, if necessary):
cat("Loading data. Please wait...\n")

if(fields.name == rean.name && subdaily == FALSE){ # Load daily psl data of all years in the reanalysis case:
    psleuFull <-array(NA,c(1, 1, n.years, 365, n.pos.lat, n.pos.lon))

    psleuFull366 <-  Load(var = psl, exp = NULL, obs = list(list(path=fields)), sdates=paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax = 366, output = 'lonlat', latmin = lat.min, latmax = lat.max, lonmin = lon.min, lonmax = lon.max, nprocs=8)
    
    # remove bisestile days to have all arrays with the same dimensions:
    cat("Removing bisestile days. Please wait...\n")
    psleuFull[,,,,,] <- psleuFull366$obs[,,,1:365,,]

    for(y in year.start:year.end){
        y2 <- y - year.start + 1
        if(n.days.in.a.year(y) == 366) psleuFull[,,y2,60:365,,] <- psleuFull366$obs[,,y2,61:366,,] # take the march to december period removing the 29th of February
    }

    psleuFull366$obs <- NULL
    gc()

 
         
    # convert psl in daily anomalies with the LOESS filter:
    cat("Calculating anomalies. Please wait...\n")
    year.end.clim <- year.end # - 1 # last year for computation of rean climatology (unless year.end has data available for all months, it's better to set it to the previous year)
    n.years.clim <- year.end.clim - year.start + 1

    psleuFull_no_last_year <- psleuFull[1,1,1:n.years.clim,,,,drop=FALSE]
    
    pslPeriodClim <- apply(psleuFull_no_last_year, c(1,2,4,5,6), mean, na.rm=T)
    
    rm(psleuFull_no_last_year)
    gc()
    
    if(LOESS == TRUE){
        pslPeriodClimLoess <- array(NA, dim(pslPeriodClim))
        
        for(i in 1:n.pos.lat){
            for(j in 1:n.pos.lon){
                my.data <- data.frame(ens.mean=rep(pslPeriodClim[1,1,,i,j],3), day=1:(365*3))
                my.loess <- loess(ens.mean ~ day, my.data, span=0.35)
                pslPeriodClimLoess[1,1,,i,j] <- predict(my.loess)[366:730]
            }
        }

        ## for Paco:
        plot(rep(pslPeriodClim[1,1,,44,45],2), type="l", col="gray", add=T) #, xaxt="n", xlab="",ylab="")
        lines(rep(pslPeriodClimLoess[1,1,,44,45],2), type="l", col="black") #, xaxt="n", xlab="",ylab="")

        plot(predict(my.loess), type="l", col="black", xaxt="n") #, xaxt="n", xlab="",ylab="")
        axis(1, at=c(0,366,730), labels=c(0,366,730))

        clim.rean <- pslPeriodClimLoess[1,1,,,] 
        save(clim.rean, file="~/clim_rean.RData")       


        
        #axis(1, at=c(0,31,59,90,120,150,180,210), labels=c(0,31,59,90,120,150,180,210))
        
        #rm(pslPeriodClim)
        gc()

        pslPeriodClim2 <- InsertDim(pslPeriodClimLoess, 3, n.years)
        
    } else { # leave the daily climatology to compute the anomalies:
        pslPeriodClim2  <- InsertDim(pslPeriodClim, 3, n.years)
        
        rm(pslPeriodClim)
        gc()
    }
    
    ## s4.data <- data.frame(s4=pslPeriodClim[1,], day=1:216)
    ## s4.loess <- loess(s4 ~ day, s4.data, span=0.35)
    ## s4.pred <- predict(s4.loess)
        
    psleuFull <- psleuFull - pslPeriodClim2    
    rm(pslPeriodClim2)
    gc()

} # close if on fields.name == rean and subdaily == FALSE){




if(fields.name == ECMWF_S4.name){ # in the forecast case, we load only the data for 1 start month at time and all the lead times (since each month needs ~3 GB of memory)


    
  for(startM in 1:12){                                      # start month (1=January, 12=December)  [bypassed by the optional arguments of the script]

    start.month <- startM

    clim <- climLOESS <- list()
    
    if(start.month <= 9) {start.month.char <- paste0("0",as.character(start.month))} else {start.month.char <- start.month}

    fields2 <- gsub("\\$STORE_FREQ\\$","daily",fields)
    fields3 <- gsub("\\$VAR_NAME\\$",psl,fields2)

    years <- year.start:year.end
    n.years.full <- length(years)

        
    ## only for Paco's climatology:
    psleuFull <- Load(var = psl, exp = list(list(path=fields)), obs = NULL, sdates=paste0(years, start.month.char,'01'), dimnames=list(member=member.name), nmember=n.members, leadtimemax=n.leadtimes, storefreq='daily', output = 'lonlat', latmin = lat.min, latmax = lat.max, lonmin = lon.min, lonmax = lon.max, nprocs=8)$mod


         # convert psl in daily anomalies with the LOESS filter:
         cat("Calculating anomalies. Please wait...\n")
         
    
            pslPeriodClim <- apply(psleuFull, c(1,4,5,6), mean, na.rm=T)

            pslPeriodClimLoess <- pslPeriodClim
             
            for(i in 1:n.pos.lat){
                for(j in 1:n.pos.lon){
                    my.data <- data.frame(ens.mean=pslPeriodClim[1,,i,j], day=1:n.leadtimes)
                    my.loess <- loess(ens.mean ~ day, my.data, span=0.35)
                    pslPeriodClimLoess[1,,i,j] <- predict(my.loess)
                }
            }

            ## for Paco:
            #plot(pslPeriodClim[1,1:215,44,45], type="l", col="orange", xaxt="n", xlab="",ylab="")
            #lines(pslPeriodClimLoess[1,1:215,44,45], type="l", col="orange", cex=5, xaxt="n", xlab="",ylab="")

            clim[[startM]] <- pslPeriodClim[1,,,]
            climLOESS[[startM]] <- pslPeriodClimLoess[1,,,]

            save(clim, climLOESS, file=paste0("/esarchive/scratch/ncortesi/BSC/RESILIENCE/LOESS filter/clim_S4_startdate_",startM,".RData"))
            #axis(1, at=c(0,31,59,90,120,150,180,210), labels=c(0,31,59,90,120,150,180,210))

             
            #rm(pslPeriodClim)
            gc()

            #pslPeriodClimDos <- InsertDim(InsertDim(pslPeriodClimLoess, 2, n.years.full), 2, n.members)
         

    
     ## s4.data <- data.frame(s4=pslPeriodClim[1,], day=1:216)
     ## s4.loess <- loess(s4 ~ day, s4.data, span=0.35)
     ## s4.pred <- predict(s4.loess)
        
     #psleuFull <- psleuFull - pslPeriodClimDos    
     #rm(pslPeriodClimDos)
     #gc()

        } # close loop on start.month


    
    
} # close if on fields.name=forecasts.name


## When you have all climatology of all start dates saved, run:

rm(list=ls())
my.month.short <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec","Jan","Feb","Mar","Apr","May","June","Jul")
my.col <- c('#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928')

load("/esarchive/scratch/ncortesi/BSC/RESILIENCE/LOESS filter/clim_rean.RData")

clim.LOESS <- clim.daily <- list()
for(m in 1:12){
    load(paste0("/esarchive/scratch/ncortesi/BSC/RESILIENCE/LOESS filter/clim_S4_startdate_",m,".RData"))
    clim.LOESS[[m]] <- climLOESS[[m]]
    clim.daily[[m]] <- clim[[m]]
}


## chose a point:
plat <- 44
plon <- 1 ##45

## reanalysis climatology:
plot(c(clim.rean[1:365,plat,plon],clim.rean[1:216,plat,plon]), type="l", col="black", xaxt="n", xlab="Start date", ylim=c(min(clim.rean[1:365,plat,plon])-0.5,max(clim.rean[1:365,plat,plon])+1), ylab="Wind speed (m/s)")
axis(1, at=c(0,31,59,90,120,151,181,212,243,273,304,334,365,393,424,454,485,515,546), labels=my.month.short)

## add LOESS climatology for each start date:
lines(clim.LOESS[[1]][1:216,plat,plon], type="l", col=my.col[1], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,1,2001)),clim.LOESS[[2]][1:216,plat,plon]), type="l", col=my.col[2], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,2,2001)),clim.LOESS[[3]][1:216,plat,plon]), type="l", col=my.col[3], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,3,2001)),clim.LOESS[[4]][1:216,plat,plon]), type="l", col=my.col[4], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,4,2001)),clim.LOESS[[5]][1:216,plat,plon]), type="l", col=my.col[5], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,5,2001)),clim.LOESS[[6]][1:216,plat,plon]), type="l", col=my.col[6], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,6,2001)),clim.LOESS[[7]][1:216,plat,plon]), type="l", col=my.col[7], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,7,2001)),clim.LOESS[[8]][1:216,plat,plon]), type="l", col=my.col[8], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,8,2001)),clim.LOESS[[9]][1:216,plat,plon]), type="l", col=my.col[9], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,9,2001)),clim.LOESS[[10]][1:216,plat,plon]), type="l", col=my.col[10], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,10,2001)),clim.LOESS[[11]][1:216,plat,plon]), type="l", col=my.col[11], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,11,2001)),clim.LOESS[[12]][1:216,plat,plon]), type="l", col=my.col[12], cex=5, xaxt="n", xlab="",ylab="")

legend("topright", my.month.short[1:12],  lty=c(1,1), lwd=c(2.5,2.5), col=my.col, bty="n")



## add daily climatology for each start date:
lines(clim.daily[[1]][1:216,plat,plon], type="l", col=my.col[1], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,1,2001)),clim.daily[[2]][1:216,plat,plon]), type="l", col=my.col[2], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,2,2001)),clim.daily[[3]][1:216,plat,plon]), type="l", col=my.col[3], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,3,2001)),clim.daily[[4]][1:216,plat,plon]), type="l", col=my.col[4], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,4,2001)),clim.daily[[5]][1:216,plat,plon]), type="l", col=my.col[5], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,5,2001)),clim.daily[[6]][1:216,plat,plon]), type="l", col=my.col[6], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,6,2001)),clim.daily[[7]][1:216,plat,plon]), type="l", col=my.col[7], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,7,2001)),clim.daily[[8]][1:216,plat,plon]), type="l", col=my.col[8], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,8,2001)),clim.daily[[9]][1:216,plat,plon]), type="l", col=my.col[9], cex=5, xaxt="n", xlab="",ylab="")
lines(c(rep(NA,n.days.in.a.monthly.period(1,9,2001)),clim.daily[[10]][1:216,plat,plon]), type="l", col=my.col[10], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,10,2001)),clim.daily[[11]][1:216,plat,plon]), type="l", col=my.col[11], cex=5, xaxt="n", xlab="",ylab="")
##lines(c(rep(NA,n.days.in.a.monthly.period(1,11,2001)),clim.daily[[12]][1:216,plat,plon]), type="l", col=my.col[12], cex=5, xaxt="n", xlab="",ylab="")

