Project

General

Profile

Download (29.3 KB) Statistics
| Branch: | Revision:
1
runGAMCAI <- function(i) {            # loop over dates
2
  
3
  #date<-strptime(dates[i], "%Y%m%d")   # interpolation date being processed
4
  date<-strptime(sampling_dat$date[i], "%Y%m%d")   # interpolation date being processed
5
  month<-strftime(date, "%m")          # current month of the date being processed
6
  LST_month<-paste("mm_",month,sep="") # name of LST month to be matched
7
  
8
  #Adding layer LST to the raster stack
9
  
10
  pos<-match(LST_month,layerNames(s_raster)) #Find column with the current month for instance mm12
11
  r1<-raster(s_raster,layer=pos)             #Select layer from stack
12
  layerNames(r1)<-"LST"
13
  s_raster<-addLayer(s_raster,r1)            #Adding current month
14
  
15
  ###Regression part 1: Creating a validation dataset by creating training and testing datasets
16
  
17
  mod_LST <-ghcn.subsets[[i]][,match(LST_month, names(ghcn.subsets[[i]]))]  #Match interpolation date and monthly LST average
18
  ghcn.subsets[[i]] = transform(ghcn.subsets[[i]],LST = mod_LST)            #Add the variable LST to the subset dataset
19
  #n<-nrow(ghcn.subsets[[i]])
20
  #ns<-n-round(n*prop)   #Create a sample from the data frame with 70% of the rows
21
  #nv<-n-ns              #create a sample for validation with prop of the rows
22
  #ind.training <- sample(nrow(ghcn.subsets[[i]]), size=ns, replace=FALSE) #This selects the index position for 70% of the rows taken randomly
23
  ind.training<-sampling[[i]]
24
  ind.testing <- setdiff(1:nrow(ghcn.subsets[[i]]), ind.training)
25
  data_s <- ghcn.subsets[[i]][ind.training, ]   #Training dataset currently used in the modeling
26
  data_v <- ghcn.subsets[[i]][ind.testing, ]    #Testing/validation dataset using input sampling
27
  
28
  ns<-nrow(data_s)
29
  nv<-nrow(data_v)
30
  #i=1
31
  date_proc<-sampling_dat$date[i]
32
  date_proc<-strptime(sampling_dat$date[i], "%Y%m%d")   # interpolation date being processed
33
  mo<-as.integer(strftime(date_proc, "%m"))          # current month of the date being processed
34
  day<-as.integer(strftime(date_proc, "%d"))
35
  year<-as.integer(strftime(date_proc, "%Y"))
36

    
37
  datelabel=format(ISOdate(year,mo,day),"%b %d, %Y")
38
  
39
  ###########
40
  #  STEP 1 - LST 10 year monthly averages: THIS IS NOT USED IN CAE
41
  ###########
42

    
43
  themolst<-raster(molst,mo) #current month being processed saved in a raster image
44
  plot(themolst)
45
  
46
  ###########
47
  # STEP 2 - Weather station means across same days: Monthly mean calculation
48
  ###########
49
  
50
  modst=dst[dst$month==mo,] #Subsetting dataset for the relevant month of the date being processed
51
  
52
  ##########
53
  # STEP 3 - get LST at stations
54
  ##########
55
  
56
  sta_lola=modst[,c("lon","lat")] #Extracting locations of stations for the current month..
57
  
58
  proj_str="+proj=lcc +lat_1=43 +lat_2=45.5 +lat_0=41.75 +lon_0=-120.5 +x_0=400000 +y_0=0 +ellps=GRS80 +units=m +no_defs";
59
  lookup<-function(r,lat,lon) {
60
    xy<-project(cbind(lon,lat),proj_str);
61
    cidx<-cellFromXY(r,xy);
62
    return(r[cidx])
63
  }
64
  sta_tmax_from_lst=lookup(themolst,sta_lola$lat,sta_lola$lon) #Extracted values of LST for the stations
65
  
66
  #########
67
  # STEP 4 - bias at stations     
68
  #########
69
  
70
  sta_bias=sta_tmax_from_lst-modst$TMax; #That is the difference between the monthly LST mean and monthly station mean
71
  #Added by Benoit
72
  modst$LSTD_bias<-sta_bias  #Adding bias to data frame modst containning the monthly average for 10 years
73
  
74
  bias_xy=project(as.matrix(sta_lola),proj_str)
75
#   png(paste("LST_TMax_scatterplot_",dates[i],out_prefix,".png", sep=""))
76
#   plot(modst$TMax,sta_tmax_from_lst,xlab="Station mo Tmax",ylab="LST mo Tmax",main=paste("LST vs TMax for",datelabel,sep=" "))
77
#   abline(0,1)
78
#   dev.off()
79
  
80
  #added by Benoit 
81
  #x<-ghcn.subsets[[i]]  #Holds both training and testing for instance 161 rows for Jan 1
82
  x<-data_v
83
  d<-data_s
84
  
85
  pos<-match("value",names(d)) #Find column with name "value"
86
  #names(d)[pos]<-c("dailyTmax")
87
  names(d)[pos]<-y_var_name
88
  names(x)[pos]<-y_var_name
89
  #names(x)[pos]<-c("dailyTmax")
90
  d$dailyTmax=(as.numeric(d$dailyTmax))/10 #stored as 1/10 degree C to allow integer storage
91
  x$dailyTmax=(as.numeric(x$dailyTmax))/10 #stored as 1/10 degree C to allow integer storage
92
  pos<-match("station",names(d)) #Find column with name "value"
93
  names(d)[pos]<-c("id")
94
  names(x)[pos]<-c("id")
95
  names(modst)[1]<-c("id")       #modst contains the average tmax per month for every stations...
96
  dmoday=merge(modst,d,by="id")  #LOOSING DATA HERE!!! from 113 t0 103
97
  xmoday=merge(modst,x,by="id")  #LOOSING DATA HERE!!! from 48 t0 43
98
  names(dmoday)[4]<-c("lat")
99
  names(dmoday)[5]<-c("lon")     #dmoday contains all the the information: BIAS, monn
100
  names(xmoday)[4]<-c("lat")
101
  names(xmoday)[5]<-c("lon")     #dmoday contains all the the information: BIAS, monn
102
  
103
  data_v<-xmoday
104
  ###
105
  
106
  #dmoday contains the daily tmax values for training with TMax being the monthly station tmax mean
107
  #xmoday contains the daily tmax values for validation with TMax being the monthly station tmax mean
108
  
109
  # windows()
110
  #png(paste("LST_TMax_scatterplot_",dates[i],out_prefix,".png", sep=""))
111
  png(paste("Daily_tmax_monthly_TMax_scatterplot_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],
112
            out_prefix,".png", sep=""))
113
  plot(dailyTmax~TMax,data=dmoday,xlab="Mo Tmax",ylab=paste("Daily for",datelabel),main="across stations in OR")
114
  #savePlot(paste("Daily_tmax_monthly_TMax_scatterplot_",dates[i],out_prefix,".png", sep=""), type="png")
115
  #png(paste("LST_TMax_scatterplot_",dates[i],out_prefix,".png", sep=""))
116
  dev.off()
117
  
118
  ########
119
  # STEP 5 - interpolate bias/climatology
120
  ########
121
  
122
  # ?? include covariates like elev, distance to coast, cloud frequency, tree height
123
  #library(fields)
124
  #windows()
125
  #quilt.plot(sta_lola,sta_bias,main="Bias at stations",asp=1)
126
  #US(add=T,col="magenta",lwd=2)
127
  #fitbias<-Tps(bias_xy,sta_bias) #use TPS or krige
128
  
129
  #Adding options to use only training stations: 07/11/2012
130
  bias_xy<-project(as.matrix(sta_lola),proj_str)
131
  clim_xy<-project(as.matrix(sta_lola),proj_str)
132
  #bias_xy2=project(as.matrix(c(dmoday$lon,dmoday$lat),proj_str)
133
  if(bias_val==1){
134
    sta_bias<-dmoday$LSTD_bias
135
    bias_xy<-cbind(dmoday$x_OR83M,dmoday$y_OR83M)
136
  }
137
  
138
  sta_clim<-modst$TMax #This contains the monthly climatology...
139
  
140
  #fitbias<-Krig(bias_xy,sta_bias,theta=1e5) #use TPS or krige 
141
  fitclim<-Krig(clim_xy,sta_clim,theta=1e5)
142
  
143
  #The output is a krig object using fields
144
  #mod9a<-fitbias
145
  mod9a<-fitclim
146
  
147
  # Creating plot of bias surface and saving it
148
  #X11()
149
  png(paste("Climtology_surface_LST_TMax_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],
150
            out_prefix,".png", sep="")) #Create file to write a plot
151
  datelabel2=format(ISOdate(year,mo,day),"%B ") #added by Benoit, label
152
  surface(fitclim,col=rev(terrain.colors(100)),asp=1,main=paste("Interpolated clim for",datelabel2,sep=" ")) #Plot to file
153
  #savePlot(paste("Bias_surface_LST_TMax_",dates[i],out_prefix,".png", sep=""), type="png")
154
  dev.off()  #Release the hold to the file
155
  
156
  #US(add=T,col="magenta",lwd=2)
157
  
158
  ##########
159
  # STEP 7 - interpolate delta across space
160
  ##########
161
  
162
  daily_sta_lola=dmoday[,c("lon","lat")] #could be same as before but why assume merge does this - assume not
163
  daily_sta_xy=project(as.matrix(daily_sta_lola),proj_str)
164
  daily_delta=dmoday$dailyTmax-dmoday$TMax
165
  
166
  daily_deltaclim<-dmoday$dailyTmax-dmoday$TMax
167
  daily_deltaclim_v<-data_v$dailyTmax-data_v$TMax  #For validation
168
  #dmoday$daily_deltaclim <-daily_deltaclim
169
  #fitdelta<-Tps(daily_sta_xy,daily_delta) #use TPS or krige
170
  fitdelta<-Krig(daily_sta_xy,daily_delta,theta=1e5) #use TPS or krige
171
  fitdeltaclim<-Krig(daily_sta_xy,daily_deltaclim,theta=1e5) #use TPS or krige
172
  
173
  #Kriging using fields package
174
  #mod9b<-fitdelta
175
  mod9b<-fitdeltaclim
176
  # Creating plot of bias surface and saving it
177
  #X11()
178
  png(paste("Deltaclim_surface_TMax_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],
179
            out_prefix,".png", sep=""))
180
  surface(fitdeltaclim,col=rev(terrain.colors(100)),asp=1,main=paste("Interpolated deltaclim for",datelabel,sep=" "))
181
  #savePlot(paste("Delta_surface_LST_TMax_",dates[i],out_prefix,".png", sep=""), type="png")
182
  dev.off()
183
  #US(add=T,col="magenta",lwd=2)
184
  #
185
  
186
  #### Added by Benoit on 06/19
187
  data_s<-dmoday #put the 
188
  #data_s$daily_delta<-daily_delta
189
  data_s$daily_deltaclim<-daily_deltaclim
190
  data_v$daily_deltaclim<-daily_deltaclim_v
191
  #data_s$y_var<-daily_delta  #y_var is the variable currently being modeled, may be better with BIAS!!
192
  #data_s$y_var<-data_s$LSTD_bias
193
  #### Added by Benoit ends
194
  
195
  #########
196
  # STEP 8 - assemble final answer - T= LST+Bias(interpolated)+delta(interpolated)
197
  #                                  T= clim(interpolated) + deltaclim(interpolated)
198
  #########
199

    
200
  #bias_rast=interpolate(themolst,fitbias) #interpolation using function from raster package
201
  clim_rast=interpolate(themolst,fitclim) #interpolation using function from raster package
202
  #themolst is raster layer, fitbias is "Krig" object from bias surface
203
  #plot(bias_rast,main="Raster bias") #This not displaying...
204
  
205
  #Saving kriged surface in raster images
206
  data_name<-paste("clim_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],sep="")
207
  raster_name<-paste("CAI_",data_name,out_prefix,".rst", sep="")
208
  writeRaster(clim_rast, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
209
  
210
  #daily_delta_rast=interpolate(themolst,fitdelta) #Interpolation of the bias surface...
211
  daily_deltaclim_rast=interpolate(themolst,fitdeltaclim) #Interpolation of the bias surface...
212
  
213
  #plot(daily_delta_rast,main="Raster Daily Delta")
214
  
215
  #Saving kriged surface in raster images
216
  data_name<-paste("deltaclim_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],sep="")
217
  raster_name<-paste("CAI_",data_name,out_prefix,".rst", sep="")
218
  writeRaster(daily_deltaclim_rast, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
219
  
220
  #tmax_predicted=themolst+daily_delta_rast-bias_rast #Final surface  as a raster layer...eqt ok
221
  tmax_predicted<-daily_deltaclim_rast + clim_rast #Final surface  as a raster layer...
222
  #tmp6<-data_s$daily_deltaclim +data_s$TMax
223
  #tmp7<-extract(tmax_predicted,data_s)
224
  #plot(tmax_predicted,main="Predicted daily")
225
  
226
  #Saving kriged surface in raster images
227
  data_name<-paste("tmax_predicted_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],sep="")
228
  raster_name<-paste("CAI_",data_name,out_prefix,".rst", sep="")
229
  writeRaster(tmax_predicted, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
230
  
231
  ########
232
  # check: assessment of results: validation
233
  ########
234
  RMSE<-function(x,y) {return(mean((x-y)^2)^0.5)}
235
  MAE_fun<-function(x,y) {return(mean(abs(x-y)))}
236
  #ME_fun<-function(x,y){return(mean(abs(y)))}
237
  #FIT ASSESSMENT
238
  sta_pred_data_s=lookup(tmax_predicted,data_s$lat,data_s$lon)
239
  rmse_fit=RMSE(sta_pred_data_s,data_s$dailyTmax)
240
  mae_fit=MAE_fun(sta_pred_data_s,data_s$dailyTmax)
241
    
242
  sta_pred=lookup(tmax_predicted,data_v$lat,data_v$lon)
243
  #sta_pred=lookup(tmax_predicted,daily_sta_lola$lat,daily_sta_lola$lon)
244
  #rmse=RMSE(sta_pred,dmoday$dailyTmax)
245
  #pos<-match("value",names(data_v)) #Find column with name "value"
246
  #names(data_v)[pos]<-c("dailyTmax")
247
  tmax<-data_v$dailyTmax
248
  #data_v$dailyTmax<-tmax
249
  rmse=RMSE(sta_pred,tmax)
250
  mae<-MAE_fun(sta_pred,tmax)
251
  r2<-cor(sta_pred,tmax)^2              #R2, coef. of var
252
  me<-mean(sta_pred-tmax)
253
 
254
  #plot(sta_pred~dmoday$dailyTmax,xlab=paste("Actual daily for",datelabel),ylab="Pred daily",main=paste("RMSE=",rmse))
255
  
256
  png(paste("Predicted_tmax_versus_observed_scatterplot_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",
257
            sampling_dat$run_samp[i],out_prefix,".png", sep=""))
258
  plot(sta_pred~tmax,xlab=paste("Actual daily for",datelabel),ylab="Pred daily",main=paste("RMSE=",rmse))
259
  abline(0,1)
260
  #savePlot(paste("Predicted_tmax_versus_observed_scatterplot_",dates[i],out_prefix,".png", sep=""), type="png")
261
  dev.off()
262
  #resid=sta_pred-dmoday$dailyTmax
263
  resid=sta_pred-tmax
264
  #quilt.plot(daily_sta_lola,resid)
265
  
266
  
267
  
268
  ###BEFORE GAM prediction the data object must be transformed to SDF
269
  
270
  coords<- data_v[,c('x_OR83M','y_OR83M')]
271
  coordinates(data_v)<-coords
272
  proj4string(data_v)<-CRS  #Need to assign coordinates...
273
  coords<- data_s[,c('x_OR83M','y_OR83M')]
274
  coordinates(data_s)<-coords
275
  proj4string(data_s)<-CRS  #Need to assign coordinates..
276
  
277
  ns<-nrow(data_s) #This is added to because some loss of data might have happened because of the averaging...
278
  nv<-nrow(data_v)
279
  
280
  ###GAM PREDICTION
281
  
282
  #data_s$y_var<-data_s$dailyTmax  #This shoudl be changed for any variable!!!
283
  #data_v$y_var<-data_v$dailyTmax
284
  #data_v$y_var<-data_v$daily_deltaclim
285
  data_s$y_var<-data_s$daily_deltaclim
286
  data_v$y_var<-data_v$daily_deltaclim
287
  
288
  if (climgam==1){
289
    data_s$y_var<-data_s$TMax
290
    data_v$y_var<-data_v$TMax
291
  }
292
  
293
  #Model and response variable can be changed without affecting the script
294
  
295
  formula1 <- as.formula("y_var ~ s(lat) + s(lon) + s(ELEV_SRTM)", env=.GlobalEnv)
296
  formula2 <- as.formula("y_var~ s(lat,lon)+ s(ELEV_SRTM)", env=.GlobalEnv)
297
  formula3 <- as.formula("y_var~ s(lat) + s (lon) + s (ELEV_SRTM) +  s (Northness)+ s (Eastness) + s(DISTOC)", env=.GlobalEnv)
298
  formula4 <- as.formula("y_var~ s(lat) + s (lon) + s(ELEV_SRTM) + s(Northness) + s (Eastness) + s(DISTOC) + s(LST)", env=.GlobalEnv)
299
  formula5 <- as.formula("y_var~ s(lat,lon) +s(ELEV_SRTM) + s(Northness,Eastness) + s(DISTOC) + s(LST)", env=.GlobalEnv)
300
  formula6 <- as.formula("y_var~ s(lat,lon) +s(ELEV_SRTM) + s(Northness,Eastness) + s(DISTOC) + s(LST)+s(LC1)", env=.GlobalEnv)
301
  formula7 <- as.formula("y_var~ s(lat,lon) +s(ELEV_SRTM) + s(Northness,Eastness) + s(DISTOC) + s(LST)+s(LC3)", env=.GlobalEnv)
302
  formula8 <- as.formula("y_var~ s(lat,lon) +s(ELEV_SRTM) + s(Northness,Eastness) + s(DISTOC) + s(LST) + s(LC1,LC3)", env=.GlobalEnv)
303
  
304
  mod1<- try(gam(formula1, data=data_s))
305
  mod2<- try(gam(formula2, data=data_s)) #modified nesting....from 3 to 2
306
  mod3<- try(gam(formula3, data=data_s))
307
  mod4<- try(gam(formula4, data=data_s))
308
  mod5<- try(gam(formula5, data=data_s))
309
  mod6<- try(gam(formula6, data=data_s))
310
  mod7<- try(gam(formula7, data=data_s))
311
  mod8<- try(gam(formula8, data=data_s))
312

    
313
  ### Added by benoit
314
  #Store results using TPS
315
  j=nmodels+1
316
  results_RMSE[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
317
  results_RMSE[2]<- ns          #number of stations used in the training stage
318
  results_RMSE[3]<- "RMSE"
319

    
320
  results_RMSE[j+3]<- rmse  #Storing RMSE for the model j
321
  
322
  results_RMSE_f[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
323
  results_RMSE_f[2]<- ns          #number of stations used in the training stage
324
  results_RMSE_f[3]<- "RMSE_f"
325
  results_RMSE_f[j+3]<- rmse_fit  #Storing RMSE for the model j
326
  
327
  results_MAE_f[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
328
  results_MAE_f[2]<- ns          #number of stations used in the training stage
329
  results_MAE_f[3]<- "RMSE_f"
330
  results_MAE_f[j+3]<- mae_fit  #Storing RMSE for the model j
331

    
332
  results_MAE[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
333
  results_MAE[2]<- ns          #number of stations used in the training stage
334
  results_MAE[3]<- "MAE"
335
  results_MAE[j+3]<- mae  #Storing RMSE for the model j
336

    
337
  results_ME[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
338
  results_ME[2]<- ns          #number of stations used in the training stage
339
  results_ME[3]<- "ME"
340
  results_ME[j+3]<- me  #Storing RMSE for the model j
341
  
342
  results_R2[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
343
  results_R2[2]<- ns          #number of stations used in the training stage
344
  results_R2[3]<- "R2"
345
  results_R2[j+3]<- r2  #Storing RMSE for the model j
346
  
347
  pred_mod<-paste("pred_mod",j,sep="")
348
  #Adding the results back into the original dataframes.
349
  data_s[[pred_mod]]<-sta_pred_data_s
350
  data_v[[pred_mod]]<-sta_pred 
351
  
352
  #Model assessment: RMSE and then krig the residuals....!
353
  
354
  res_mod_s<- data_s$dailyTmax - data_s[[pred_mod]]           #Residuals from kriging training
355
  res_mod_v<- data_v$dailyTmax - data_v[[pred_mod]]           #Residuals from kriging validation
356
  
357
  name2<-paste("res_mod",j,sep="")
358
  data_v[[name2]]<-as.numeric(res_mod_v)
359
  data_s[[name2]]<-as.numeric(res_mod_s)
360
  
361
  #ns<-nrow(data_s) #This is added to because some loss of data might have happened because of the averaging...
362
  #nv<-nrow(data_v)
363
  browser()
364
  
365
  for (j in 1:nmodels){
366
    
367
    ##Model assessment: specific diagnostic/metrics for GAM
368
    
369
    name<-paste("mod",j,sep="")  #modj is the name of The "j" model (mod1 if j=1) 
370
    mod<-get(name)               #accessing GAM model ojbect "j"
371
    
372
    #If mod "j" is not a model object
373
    if (inherits(mod,"try-error")) {
374
      results_m1[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
375
      results_m1[1,2]<- ns        #number of stations used in the training stage
376
      results_m1[1,3]<- "AIC"
377
      results_m1[1,j+3]<- NA
378
      
379
      results_m2[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
380
      results_m2[1,2]<- ns        #number of stations used in the training 
381
      results_m2[1,3]<- "GCV"
382
      results_m2[1,j+3]<- NA
383
      
384
      results_m3[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
385
      results_m3[1,2]<- ns        #number of stations used in the training stage
386
      results_m3[1,3]<- "DEV"
387
      results_m3[1,j+3]<- NA
388
      
389
      results_RMSE_f[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
390
      results_RMSE_f[1,2]<- ns        #number of stations used in the training stage
391
      results_RMSE_f[1,3]<- "RSME_f"
392
      results_RMSE_f[1,j+3]<- NA
393
      
394
      results_MAE_f[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
395
      results_MAE_f[1,2]<- ns        #number of stations used in the training stage
396
      results_MAE_f[1,3]<- "MAE_f"
397
      results_MAE_f[1,j+3]<-NA
398
      
399
      results_R2_f[1,1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
400
      results_R2_f[1,2]<- ns            #number of stations used in the training stage
401
      results_R2_f[1,3]<- "R2_f"
402
      results_R2_f[1,j+3]<- NA     #Storing R2 for the model j
403
      
404
      
405
      results_RMSE[1,1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
406
      results_RMSE[1,2]<- ns          #number of stations used in the training stage
407
      results_RMSE[1,3]<- "RMSE"
408
      results_RMSE[1,j+3]<- NA  #Storing RMSE for the model j
409
      results_MAE[1,1]<- sampling_dat$date[i]     #storing the interpolation dates in the first column
410
      results_MAE[1,2]<- ns           #number of stations used in the training stage
411
      results_MAE[1,3]<- "MAE"
412
      results_MAE[1,j+3]<- NA    #Storing MAE for the model j
413
      results_ME[1,1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
414
      results_ME[1,2]<- ns            #number of stations used in the training stage
415
      results_ME[1,3]<- "ME"
416
      results_ME[1,j+3]<- NA      #Storing ME for the model j
417
      results_R2[1,1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
418
      results_R2[1,2]<- ns            #number of stations used in the training stage
419
      results_R2[1,3]<- "R2"
420
      results_R2[1,j+3]<- NA      #Storing R2 for the model j
421
      
422
    }
423
    
424
    #If mod is a modelobject
425
    
426
    #If mod "j" is not a model object
427
    if (inherits(mod,"gam")) {
428
      
429
      results_m1[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
430
      results_m1[1,2]<- ns        #number of stations used in the training stage
431
      results_m1[1,3]<- "AIC"
432
      results_m1[1,j+3]<- AIC (mod)
433
      
434
      results_m2[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
435
      results_m2[1,2]<- ns        #number of stations used in the training 
436
      results_m2[1,3]<- "GCV"
437
      results_m2[1,j+3]<- mod$gcv.ubre
438
      
439
      results_m3[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
440
      results_m3[1,2]<- ns        #number of stations used in the training stage
441
      results_m3[1,3]<- "DEV"
442
      results_m3[1,j+3]<- mod$deviance
443
      
444
      y_var_fit= mod$fit
445
      R2_mod_f<- cor(data_s$dailyTmax,y_var_fit, use="complete")^2
446
      #RMSE_mod_f<- sqrt(mean(res_mod_s^2,na.rm=TRUE))
447
      
448
      results_RMSE_f[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
449
      results_RMSE_f[1,2]<- ns        #number of stations used in the training stage
450
      results_RMSE_f[1,3]<- "RSME_f"
451
      #results_RMSE_f[j+3]<- sqrt(sum((y_var_fit-data_s$y_var)^2)/ns)
452
      results_RMSE_f[1,j+3]<-sqrt(mean(mod$residuals^2,na.rm=TRUE))
453
      
454
      results_MAE_f[1,1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
455
      results_MAE_f[1,2]<- ns        #number of stations used in the training stage
456
      results_MAE_f[1,3]<- "MAE_f"
457
      #results_MAE_f[j+3]<-sum(abs(y_var_fit-data_s$y_var))/ns
458
      results_MAE_f[1,j+3]<-mean(abs(mod$residuals),na.rm=TRUE)
459
      
460
      results_R2_f[1,1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
461
      results_R2_f[1,2]<- ns            #number of stations used in the training stage
462
      results_R2_f[1,3]<- "R2_f"
463
      results_R2_f[1,j+3]<- R2_mod_f      #Storing R2 for the model j
464
      
465
      ##Model assessment: general diagnostic/metrics
466
      ##validation: using the testing data
467
      if (predval==1) {
468
      
469
        ##Model assessment: specific diagnostic/metrics for GAM
470
        
471
        name<-paste("mod",j,sep="")  #modj is the name of The "j" model (mod1 if j=1) 
472
        mod<-get(name)               #accessing GAM model ojbect "j"
473
        
474
        s_sgdf<-as(s_raster,"SpatialGridDataFrame") #Conversion to spatial grid data frame
475
        
476
        rpred<- predict(mod, newdata=s_sgdf, se.fit = TRUE) #Using the coeff to predict new values.
477
        y_pred<-rpred$fit
478
        raster_pred<-r1
479
        layerNames(raster_pred)<-"y_pred"
480
        values(raster_pred)<-as.numeric(y_pred)
481
        data_name<-paste("predicted_mod",j,"_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],sep="")
482
        raster_name<-paste("GAMCAI_",data_name,out_prefix,".rst", sep="")
483
        writeRaster(raster_pred, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
484
        #writeRaster(r2, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
485
        
486
        tmax_predicted_CAI<-raster_pred + clim_rast #Final surface  as a raster layer...
487
        if (climgam==1){
488
          tmax_predicted_CAI<-raster_pred + daily_deltaclim_rast #Final surface  as a raster layer...
489
        }
490
          
491
        layerNames(tmax_predicted_CAI)<-"y_pred"
492
        data_name<-paste("predicted_mod",j,"_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],sep="")
493
        raster_name<-paste("GAMCAI_tmax_pred_",data_name,out_prefix,".rst", sep="")
494
        writeRaster(tmax_predicted_CAI, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
495
        #writeRaster(r2, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
496
        
497
        pred_sgdf<-as(tmax_predicted_CAI,"SpatialGridDataFrame") #Conversion to spatial grid data frame
498
        #rpred_val_s <- overlay(raster_pred,data_s)             #This overlays the kriged surface tmax and the location of weather stations
499
                
500
        rpred_val_s <- overlay(pred_sgdf,data_s)             #This overlays the kriged surface tmax and the location of weather stations
501
        rpred_val_v <- overlay(pred_sgdf,data_v)             #This overlays the kriged surface tmax and the location of weather stations
502
        
503
        pred_mod<-paste("pred_mod",j,sep="")
504
        #Adding the results back into the original dataframes.
505
        data_s[[pred_mod]]<-rpred_val_s$y_pred
506
        data_v[[pred_mod]]<-rpred_val_v$y_pred  
507
        
508
        #Model assessment: RMSE and then krig the residuals....!
509
        
510
        res_mod_s<- data_s$dailyTmax - data_s[[pred_mod]]           #Residuals from kriging training
511
        res_mod_v<- data_v$dailyTmax - data_v[[pred_mod]]           #Residuals from kriging validation
512
        
513
      }
514
      
515
      if (predval==0) {
516
      
517
        y_mod<- predict(mod, newdata=data_v, se.fit = TRUE) #Using the coeff to predict new values.
518
        
519
        pred_mod<-paste("pred_mod",j,sep="")
520
        #Adding the results back into the original dataframes.
521
        data_s[[pred_mod]]<-as.numeric(mod$fit)
522
        data_v[[pred_mod]]<-as.numeric(y_mod$fit)
523
        
524
        #Model assessment: RMSE and then krig the residuals....!
525
        #y_var_name<-"dailyTmax"
526
        res_mod_s<- data_s$dailyTmax - data_s[[pred_mod]]           #Residuals from kriging training
527
        res_mod_v<- data_v$dailyTmax - data_v[[pred_mod]]           #Residuals from kriging validation
528
      }
529

    
530
      ####ADDED ON JULY 20th
531
      res_mod<-res_mod_v
532
      
533
      #RMSE_mod <- sqrt(sum(res_mod^2)/nv)                 #RMSE FOR REGRESSION STEP 1: GAM  
534
      RMSE_mod<- sqrt(mean(res_mod^2,na.rm=TRUE))
535
      #MAE_mod<- sum(abs(res_mod),na.rm=TRUE)/(nv-sum(is.na(res_mod)))        #MAE from kriged surface validation
536
      MAE_mod<- mean(abs(res_mod), na.rm=TRUE)
537
      #ME_mod<- sum(res_mod,na.rm=TRUE)/(nv-sum(is.na(res_mod)))                    #ME, Mean Error or bias FOR REGRESSION STEP 1: GAM
538
      ME_mod<- mean(res_mod,na.rm=TRUE)                            #ME, Mean Error or bias FOR REGRESSION STEP 1: GAM
539
      #R2_mod<- cor(data_v$y_var,data_v[[pred_mod]])^2              #R2, coef. of var FOR REGRESSION STEP 1: GAM
540
      pred_mod<-paste("pred_mod",j,sep="")
541
      R2_mod<- cor(data_v$dailyTmax,data_v[[pred_mod]], use="complete")^2
542
      results_RMSE[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
543
      results_RMSE[2]<- ns          #number of stations used in the training stage
544
      results_RMSE[3]<- "RMSE"
545
      results_RMSE[j+3]<- RMSE_mod  #Storing RMSE for the model j
546
      results_MAE[1]<- sampling_dat$date[i]     #storing the interpolation dates in the first column
547
      results_MAE[2]<- ns           #number of stations used in the training stage
548
      results_MAE[3]<- "MAE"
549
      results_MAE[j+3]<- MAE_mod    #Storing MAE for the model j
550
      results_ME[1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
551
      results_ME[2]<- ns            #number of stations used in the training stage
552
      results_ME[3]<- "ME"
553
      results_ME[j+3]<- ME_mod      #Storing ME for the model j
554
      results_R2[1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
555
      results_R2[2]<- ns            #number of stations used in the training stage
556
      results_R2[3]<- "R2"
557
      results_R2[j+3]<- R2_mod      #Storing R2 for the model j
558
      
559
      #Saving residuals and prediction in the dataframes: tmax predicted from GAM
560

    
561
      name2<-paste("res_mod",j,sep="")
562
      data_v[[name2]]<-as.numeric(res_mod_v)
563
      data_s[[name2]]<-as.numeric(res_mod_s)
564
      #end of loop calculating RMSE
565
    }
566
  }
567
  
568
  #if (i==length(dates)){
569
  
570
  
571
  #Specific diagnostic measures related to the testing datasets
572
  
573
  results_table_RMSE<-as.data.frame(results_RMSE)
574
  results_table_MAE<-as.data.frame(results_MAE)
575
  results_table_ME<-as.data.frame(results_ME)
576
  results_table_R2<-as.data.frame(results_R2)
577
  results_table_RMSE_f<-as.data.frame(results_RMSE_f)
578
  results_table_MAE_f<-as.data.frame(results_MAE_f)
579
  results_table_R2_f<-as.data.frame(results_R2_f)
580
  
581
  results_table_m1<-as.data.frame(results_m1)
582
  results_table_m2<-as.data.frame(results_m2)
583
  results_table_m3<-as.data.frame(results_m3)
584
  
585
  tb_metrics1<-rbind(results_table_RMSE,results_table_MAE, results_table_ME, 
586
                     results_table_R2,results_table_RMSE_f,results_table_MAE_f,results_table_R2_f)   #
587
  tb_metrics2<-rbind(results_table_m1,results_table_m2, results_table_m3)
588
  cname<-c("dates","ns","metric","mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7","mod8","mod9")
589
  colnames(tb_metrics1)<-cname
590
  cname<-c("dates","ns","metric","mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7","mod8")
591
  colnames(tb_metrics2)<-cname
592
  #colnames(results_table_RMSE)<-cname
593
  #colnames(results_table_RMSE_f)<-cname
594
  #tb_diagnostic1<-results_table_RMSE      #measures of validation
595
  #tb_diagnostic2<-results_table_RMSE_f    #measures of fit
596
  
597
  #write.table(tb_diagnostic1, file= paste(path,"/","results_fusion_Assessment_measure1",out_prefix,".txt",sep=""), sep=",")
598
  
599
  #}  
600
  print(paste(sampling_dat$date[i],"processed"))
601
  # Kriging object may need to be modified...because it contains the full image of prediction!!
602
  ##loop through model objects data frame and set field to zero...
603

    
604
  mod_obj<-list(mod1,mod2,mod3,mod4,mod5,mod6,mod7,mod8,mod9a,mod9b)
605
  names(mod_obj)<-c("mod1","mod2","mod3","mod4","mod5","mod6","mod7","mod8","mod9a","mod9b") #generate names automatically??
606
  #results_list<-list(data_s,data_v,tb_metrics1,tb_metrics2)
607
  results_list<-list(data_s,data_v,tb_metrics1,tb_metrics2,mod_obj)
608
  names(results_list)<-c("data_s","data_v","tb_metrics1","tb_metrics2","mod_obj")
609
  save(results_list,file= paste(path,"/","results_list_metrics_objects_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i],
610
                                out_prefix,".RData",sep=""))
611
  return(results_list)
612
  #return(tb_diagnostic1)
613
}
(3-3/32)