Project

General

Profile

Download (30 KB) Statistics
| Branch: | Revision:
1
runGAMFusion <- function(i) {            # loop over dates
2
  
3
  date<-strptime(sampling_dat$date[i], "%Y%m%d")   # interpolation date being processed
4
  month<-strftime(date, "%m")          # current month of the date being processed
5
  LST_month<-paste("mm_",month,sep="") # name of LST month to be matched
6
  proj_str<-proj4string(dst)
7
  #Adding layer LST to the raster stack
8

    
9
  pos<-match("LST",layerNames(s_raster)) #Find the position of the layer with name "LST", if not present pos=NA
10
  s_raster<-dropLayer(s_raster,pos)      # If it exists drop layer
11
  pos<-match(LST_month,layerNames(s_raster)) #Find column with the current month for instance mm12
12
  r1<-raster(s_raster,layer=pos)             #Select layer from stack
13
  layerNames(r1)<-"LST"
14
  #Screen for extreme values" 10/30
15
  #min_val<-(-15+273.16) #if values less than -15C then screen out (note the Kelvin units that will need to be changed later in all datasets)
16
  #r1[r1 < (min_val)]<-NA
17
  s_raster<-addLayer(s_raster,r1)            #Adding current month
18
  
19
  pos<-match("elev",layerNames(s_raster))
20
  layerNames(s_raster)[pos]<-"elev_1"
21
  ###Regression part 1: Creating a validation dataset by creating training and testing datasets
22
  data_day<-ghcn.subsets[[i]]
23
  mod_LST <- ghcn.subsets[[i]][,match(LST_month, names(ghcn.subsets[[i]]))]  #Match interpolation date and monthly LST average
24
  data_day$LST <- as.data.frame(mod_LST)[,1] #Add the variable LST to the dataset
25
  dst$LST<-dst[[LST_month]] #Add the variable LST to the monthly dataset
26
  
27
  ind.training<-sampling[[i]]
28
  ind.testing <- setdiff(1:nrow(data_day), ind.training)
29
  data_s <- data_day[ind.training, ]   #Training dataset currently used in the modeling
30
  data_v <- data_day[ind.testing, ]    #Testing/validation dataset using input sampling
31
  
32
  ns<-nrow(data_s)
33
  nv<-nrow(data_v)
34
  #i=1
35
  date_proc<-sampling_dat$date[i]
36
  date_proc<-strptime(sampling_dat$date[i], "%Y%m%d")   # interpolation date being processed
37
  mo<-as.integer(strftime(date_proc, "%m"))          # current month of the date being processed
38
  day<-as.integer(strftime(date_proc, "%d"))
39
  year<-as.integer(strftime(date_proc, "%Y"))
40

    
41
  datelabel=format(ISOdate(year,mo,day),"%b %d, %Y")
42
  
43
  ###########
44
  #  STEP 1 - LST 10 year monthly averages
45
  ###########
46
  pos<-match("LST",layerNames(s_raster)) #Find the position of the layer with name "LST", 
47
  themolst<-raster(s_raster,layer=pos)
48
  #themolst<-raster(molst,mo) #current month being processed saved in a raster image
49
  #min_val<-(-15)     #Screening for extreme values
50
  #themolst[themolst < (min_val)]<-NA
51
  
52
  ###########
53
  # STEP 2 - Weather station means across same days: Monthly mean calculation
54
  ###########
55
  
56
  modst<-dst[dst$month==mo,] #Subsetting dataset for the relevant month of the date being processed
57
  
58
  ##########
59
  # STEP 3 - get LST at stations  
60
  ##########
61
  
62
  #sta_lola=modst[,c("lon","lat")] #Extracting locations of stations for the current month..
63
  
64
  #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";
65
  lookup<-function(r,lat,lon) {
66
    xy<-project(cbind(lon,lat),proj_str);
67
    cidx<-cellFromXY(r,xy);
68
    return(r[cidx])
69
  }
70
  #sta_tmax_from_lst=lookup(themolst,sta_lola$lat,sta_lola$lon) #Extracted values of LST for the stations
71
  sta_tmax_from_lst<-modst$LST
72
  #########
73
  # STEP 4 - bias at stations     
74
  #########
75
  
76
  sta_bias=sta_tmax_from_lst-modst$TMax; #That is the difference between the monthly LST mean and monthly station mean
77
  #Added by Benoit
78
  modst$LSTD_bias<-sta_bias  #Adding bias to data frame modst containning the monthly average for 10 years
79
  
80
  #bias_xy=project(as.matrix(sta_lola),proj_str)
81
  png(paste("LST_TMax_scatterplot_",sampling_dat$date[i],"_",sampling_dat$prop[i],"_",sampling_dat$run_samp[i], out_prefix,".png", sep=""))
82
  plot(modst$TMax,sta_tmax_from_lst,xlab="Station mo Tmax",ylab="LST mo Tmax",main=paste("LST vs TMax for",datelabel,sep=" "))
83
  abline(0,1)
84
  nb_point<-paste("n=",length(modst$TMax),sep="")
85
  mean_bias<-paste("LST bias= ",format(mean(modst$LSTD_bias,na.rm=TRUE),digits=3),sep="")
86
  #Add the number of data points on the plot
87
  legend("topleft",legend=c(mean_bias,nb_point),bty="n")
88
  dev.off()
89
  
90
  #added by Benoit 
91
  #x<-ghcn.subsets[[i]]  #Holds both training and testing for instance 161 rows for Jan 1
92
  x<-as.data.frame(data_v)
93
  d<-as.data.frame(data_s)
94
  #x[x$value==-999.9]<-NA
95
  for (j in 1:nrow(x)){
96
    if (x$value[j]== -999.9){
97
      x$value[j]<-NA
98
    }
99
  }
100
  for (j in 1:nrow(d)){
101
    if (d$value[j]== -999.9){
102
      d$value[j]<-NA
103
    }
104
  }
105
  #x[x$value==-999.9]<-NA
106
  #d[d$value==-999.9]<-NA
107
  pos<-match("value",names(d)) #Find column with name "value"
108
  #names(d)[pos]<-c("dailyTmax")
109
  names(d)[pos]<-y_var_name
110
  names(x)[pos]<-y_var_name
111
  #names(x)[pos]<-c("dailyTmax")
112
  pos<-match("station",names(d)) #Find column with name "value"
113
  names(d)[pos]<-c("id")
114
  names(x)[pos]<-c("id")
115
  names(modst)[1]<-c("id")       #modst contains the average tmax per month for every stations...
116
  
117
  dmoday=merge(modst,d,by="id",suffixes=c("",".y2"))  #LOOSING DATA HERE!!! from 113 t0 103
118
  xmoday=merge(modst,x,by="id",suffixes=c("",".y2"))  #LOOSING DATA HERE!!! from 48 t0 43
119
  mod_pat<-glob2rx("*.y2")   
120
  var_pat<-grep(mod_pat,names(dmoday),value=FALSE) # using grep with "value" extracts the matching names
121
  dmoday<-dmoday[,-var_pat]
122
  mod_pat<-glob2rx("*.y2")   
123
  var_pat<-grep(mod_pat,names(xmoday),value=FALSE) # using grep with "value" extracts the matching names
124
  xmoday<-xmoday[,-var_pat] #Removing duplicate columns
125
  
126
  data_v<-xmoday
127
  ###
128
  
129
  #dmoday contains the daily tmax values for training with TMax being the monthly station tmax mean
130
  #xmoday contains the daily tmax values for validation with TMax being the monthly station tmax mean
131
  
132
  png(paste("Daily_tmax_monthly_TMax_scatterplot_",sampling_dat$date[i],"_",sampling_dat$prop[i],
133
            "_",sampling_dat$run_samp[i],out_prefix,".png", sep=""))
134
  plot(dailyTmax~TMax,data=dmoday,xlab="Mo Tmax",ylab=paste("Daily for",datelabel),main="across stations in OR")
135
  dev.off()
136
  
137
  ########
138
  # STEP 5 - interpolate bias
139
  ########
140
  
141
  # ?? include covariates like elev, distance to coast, cloud frequency, tree heig
142
  #fitbias<-Tps(bias_xy,sta_bias) #use TPS or krige
143
  
144
  #Adding options to use only training stations : 07/11/2012
145
  #bias_xy=project(as.matrix(sta_lola),proj_str)
146
  #bias_xy2=project(as.matrix(c(dmoday$lon,dmoday$lat),proj_str)
147
  bias_xy<-coordinates(modst)
148
  if(bias_val==1){
149
    sta_bias<-dmoday$LSTD_bias
150
    bias_xy<-cbind(dmoday$x_OR83M,dmoday$y_OR83M)
151
  }
152
  
153
  fitbias<-Krig(bias_xy,sta_bias,theta=1e5) #use TPS or krige 
154
  #The output is a krig object using fields: modif 10/30
155
  #mod9a<-fitbias
156
  mod_krtmp1<-fitbias
157
  model_name<-paste("mod_kr","month",sep="_")
158
  assign(model_name,mod_krtmp1)
159
  
160
    
161
  ##########
162
  # STEP 7 - interpolate delta across space
163
  ##########
164
  
165
  daily_sta_lola=dmoday[,c("lon","lat")] #could be same as before but why assume merge does this - assume not
166
  daily_sta_xy=project(as.matrix(daily_sta_lola),proj_str)
167
  
168
  daily_delta=dmoday$dailyTmax-dmoday$TMax
169
  
170
  #fitdelta<-Tps(daily_sta_xy,daily_delta) #use TPS or krige
171
  fitdelta<-Krig(daily_sta_xy,daily_delta,theta=1e5) #use TPS or krige
172
  #Kriging using fields package: modif 10/30
173
  #mod9b<-fitdelta
174
  mod_krtmp2<-fitdelta
175
  model_name<-paste("mod_kr","day",sep="_")
176
  assign(model_name,mod_krtmp2)
177
  
178
  png(paste("Delta_surface_LST_TMax_",sampling_dat$date[i],"_",sampling_dat$prop[i],
179
            "_",sampling_dat$run_samp[i],out_prefix,".png", sep=""))
180
  surface(fitdelta,col=rev(terrain.colors(100)),asp=1,main=paste("Interpolated delta for",datelabel,sep=" "))
181
  dev.off()
182
  #
183
  
184
  #### Added by Benoit on 06/19
185
  data_s<-dmoday #put the 
186
  data_s$daily_delta<-daily_delta
187
  
188
  #data_s$y_var<-daily_delta  #y_var is the variable currently being modeled, may be better with BIAS!!
189
  #data_s$y_var<-data_s$LSTD_bias
190
  #### Added by Benoit ends
191
  
192
  #########
193
  # STEP 8 - assemble final answer - T=LST+Bias(interpolated)+delta(interpolated)
194
  #########
195

    
196
  bias_rast=interpolate(themolst,fitbias) #interpolation using function from raster package
197
  #themolst is raster layer, fitbias is "Krig" object from bias surface
198
  #plot(bias_rast,main="Raster bias") #This not displaying...
199
  
200
  #Saving kriged surface in raster images
201
  data_name<-paste("bias_LST_",sampling_dat$date[i],"_",sampling_dat$prop[i],
202
                   "_",sampling_dat$run_samp[i],sep="")
203
  raster_name<-paste("fusion_",data_name,out_prefix,".rst", sep="")
204
  writeRaster(bias_rast, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
205
  
206
  daily_delta_rast=interpolate(themolst,fitdelta) #Interpolation of the bias surface...
207
  
208
  #plot(daily_delta_rast,main="Raster Daily Delta")
209
  
210
  #Saving kriged surface in raster images
211
  data_name<-paste("daily_delta_",sampling_dat$date[i],"_",sampling_dat$prop[i],
212
                   "_",sampling_dat$run_samp[i],sep="")
213
  raster_name<-paste("fusion_",data_name,out_prefix,".rst", sep="")
214
  writeRaster(daily_delta_rast, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
215
  
216
  tmax_predicted=themolst+daily_delta_rast-bias_rast #Final surface  as a raster layer...
217
  #tmax_predicted=themolst+daily_delta_rast+bias_rast #Added by Benoit, why is it -bias_rast
218
  #plot(tmax_predicted,main="Predicted daily")
219
  
220
  #Saving kriged surface in raster images
221
  data_name<-paste("tmax_predicted_",sampling_dat$date[i],"_",sampling_dat$prop[i],
222
                   "_",sampling_dat$run_samp[i],sep="")
223
  raster_name<-paste("fusion_",data_name,out_prefix,".rst", sep="")
224
  writeRaster(tmax_predicted, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
225
  
226
  ########
227
  # check: assessment of results: validation
228
  ########
229
  RMSE<-function(res) {return(((mean(res,na.rm=TRUE))^2)^0.5)}
230
  MAE_fun<-function(res) {return(mean(abs(res),na.rm=TRUE))}
231
  #ME_fun<-function(x,y){return(mean(abs(y)))}
232
  #FIT ASSESSMENT
233
  sta_pred_data_s=lookup(tmax_predicted,data_s$lat,data_s$lon)
234
  
235
  rmse_fit=RMSE(sta_pred_data_s-data_s$dailyTmax)
236
  mae_fit=MAE_fun(sta_pred_data_s-data_s$dailyTmax)
237
    
238
  sta_pred=lookup(tmax_predicted,data_v$lat,data_v$lon)
239
  #sta_pred=lookup(tmax_predicted,daily_sta_lola$lat,daily_sta_lola$lon)
240
  #rmse=RMSE(sta_pred,dmoday$dailyTmax)
241
  #pos<-match("value",names(data_v)) #Find column with name "value"
242
  #names(data_v)[pos]<-c("dailyTmax")
243
  tmax<-data_v$dailyTmax
244
  #data_v$dailyTmax<-tmax
245
  rmse=RMSE(sta_pred-tmax)
246
  mae<-MAE_fun(sta_pred-tmax)
247
  r2<-cor(sta_pred,tmax)^2              #R2, coef. of var
248
  me<-mean(sta_pred-tmax,na.rm=T)
249
   
250
  png(paste("Predicted_tmax_versus_observed_scatterplot_",sampling_dat$date[i],"_",sampling_dat$prop[i],
251
            "_",sampling_dat$run_samp[i],out_prefix,".png", sep=""))
252
  plot(sta_pred~tmax,xlab=paste("Actual daily for",datelabel),ylab="Pred daily",main=paste("RMSE=",rmse))
253
  abline(0,1)
254
  dev.off()
255
  #resid=sta_pred-dmoday$dailyTmax
256
  resid=sta_pred-tmax
257
  
258
  ###BEFORE GAM prediction the data object must be transformed to SDF
259
  
260
  coords<- data_v[,c('x','y')]
261
  coordinates(data_v)<-coords
262
  proj4string(data_v)<-proj_str  #Need to assign coordinates...
263
  coords<- data_s[,c('x','y')]
264
  coordinates(data_s)<-coords
265
  proj4string(data_s)<-proj_str  #Need to assign coordinates..
266
  coords<- modst[,c('x','y')]
267
  #coordinates(modst)<-coords
268
  #proj4string(modst)<-proj_str  #Need to assign coordinates..
269
  
270
  ns<-nrow(data_s) #This is added to because some loss of data might have happened because of the averaging...
271
  nv<-nrow(data_v)
272
  
273
  ###GAM PREDICTION
274
  
275
  if (bias_prediction==1){
276
    data_s$y_var<-data_s$LSTD_bias  #This shoudl be changed for any variable!!!
277
    data_v$y_var<-data_v$LSTD_bias
278
    data_month<-modst
279
    data_month$y_var<-modst$LSTD_bias
280
  }
281

    
282
  if (bias_prediction==0){
283
    data_v$y_var<-data_v[[y_var_name]]
284
    data_s$y_var<-data_s[[y_var_name]]
285
  }
286
  
287
  #Model and response variable can be changed without affecting the script
288
  
289
  list_formulas<-vector("list",nmodels)
290
  
291
  list_formulas[[1]] <- as.formula("y_var ~ s(elev_1)", env=.GlobalEnv)
292
  list_formulas[[2]] <- as.formula("y_var ~ s(LST)", env=.GlobalEnv)
293
  list_formulas[[3]] <- as.formula("y_var ~ s(elev_1,LST)", env=.GlobalEnv)
294
  list_formulas[[4]] <- as.formula("y_var ~ s(lat) + s(lon)+ s(elev_1)", env=.GlobalEnv)
295
  list_formulas[[5]] <- as.formula("y_var ~ s(lat,lon,elev_1)", env=.GlobalEnv)
296
  list_formulas[[6]] <- as.formula("y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST)", env=.GlobalEnv)
297
  list_formulas[[7]] <- as.formula("y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST) + s(LC2)", env=.GlobalEnv)
298
  list_formulas[[8]] <- as.formula("y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST) + s(LC6)", env=.GlobalEnv)
299
  list_formulas[[9]] <- as.formula("y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST) + s(DISTOC)", env=.GlobalEnv)
300
  
301
  #list_formulas[[1]] <- as.formula("y_var ~ s(ELEV_SRTM)", env=.GlobalEnv)
302
  #list_formulas[[2]] <- as.formula("y_var ~ s(lat,lon)", env=.GlobalEnv)
303
  #list_formulas[[3]] <- as.formula("y_var~ s(lat,lon,ELEV_SRTM)", env=.GlobalEnv)
304
  #list_formulas[[4]] <- as.formula("y_var~ s(lat) + s (lon) + s (ELEV_SRTM) + s(DISTOC)", env=.GlobalEnv)
305
  #list_formulas[[5]] <- as.formula("y_var~ s(lat,lon,ELEV_SRTM) + s(Northness) + s (Eastness) + s(DISTOC)", env=.GlobalEnv)
306
  #list_formulas[[6]] <- as.formula("y_var~ s(lat,lon) +s(ELEV_SRTM) + s(Northness,Eastness) + s(DISTOC)", env=.GlobalEnv)
307
  
308
  if (bias_prediction==1){
309
    #mod1<- try(gam(formula1, data=data_month))
310
    #mod2<- try(gam(formula2, data=data_month)) #modified nesting....from 3 to 2
311
    #mod3<- try(gam(formula3, data=data_month))
312
    #mod4<- try(gam(formula4, data=data_month))
313
    #mod5<- try(gam(formula5, data=data_month))
314
    #mod6<- try(gam(formula6, data=data_month))
315
    #mod7<- try(gam(formula7, data=data_month))
316
    #mod8<- try(gam(formula8, data=data_month)) 
317
    
318
    for (j in 1:nmodels){
319
      formula<-list_formulas[[j]]
320
      mod<- try(gam(formula, data=data_month))
321
      model_name<-paste("mod",j,sep="")
322
      assign(model_name,mod) 
323
    }
324
    
325
  } else if (bias_prediction==0){      #Use daily data for direct prediction using GAM
326
    
327
    #mod1<- try(gam(formula1, data=data_s))
328
    #mod2<- try(gam(formula2, data=data_s)) #modified nesting....from 3 to 2
329
    #mod3<- try(gam(formula3, data=data_s))
330
    #mod4<- try(gam(formula4, data=data_s))
331
    #mod5<- try(gam(formula5, data=data_s))
332
    #mod6<- try(gam(formula6, data=data_s))
333
    #mod7<- try(gam(formula7, data=data_s))
334
    #mod8<- try(gam(formula8, data=data_s))
335
    
336
    for (j in 1:nmodels){
337
      formula<-list_formulas[[j]]
338
      mod<- try(gam(formula, data=data_s))
339
      model_name<-paste("mod",j,sep="")
340
      assign(model_name,mod) 
341
    }
342
    
343
  }
344

    
345
  #Added
346
  #tmax_predicted=themolst+daily_delta_rast-bias_rast #Final surface?? but daily_rst
347
  
348
  ### Added by benoit
349
  #Store results using TPS
350
  j=nmodels+1
351
  results_RMSE[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
352
  results_RMSE[2]<- ns          #number of stations used in the training stage
353
  results_RMSE[3]<- "RMSE"
354

    
355
  results_RMSE[j+3]<- rmse  #Storing RMSE for the model j
356
  
357
  results_RMSE_f[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
358
  results_RMSE_f[2]<- ns          #number of stations used in the training stage
359
  results_RMSE_f[3]<- "RMSE_f"
360
  results_RMSE_f[j+3]<- rmse_fit  #Storing RMSE for the model j
361
  
362
  results_MAE_f[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
363
  results_MAE_f[2]<- ns          #number of stations used in the training stage
364
  results_MAE_f[3]<- "RMSE_f"
365
  results_MAE_f[j+3]<- mae_fit  #Storing RMSE for the model j
366

    
367
  results_MAE[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
368
  results_MAE[2]<- ns          #number of stations used in the training stage
369
  results_MAE[3]<- "MAE"
370
  results_MAE[j+3]<- mae  #Storing RMSE for the model j
371

    
372
  results_ME[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
373
  results_ME[2]<- ns          #number of stations used in the training stage
374
  results_ME[3]<- "ME"
375
  results_ME[j+3]<- me  #Storing RMSE for the model j
376
  
377
  results_R2[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
378
  results_R2[2]<- ns          #number of stations used in the training stage
379
  results_R2[3]<- "R2"
380
  results_R2[j+3]<- r2  #Storing RMSE for the model j
381
  
382
  #ns<-nrow(data_s) #This is added to because some loss of data might have happened because of the averaging...
383
  #nv<-nrow(data_v)
384
  
385
  pred_mod<-paste("pred_mod",j,sep="")
386
  #Adding the results back into the original dataframes.
387
  data_s[[pred_mod]]<-sta_pred_data_s
388
  data_v[[pred_mod]]<-sta_pred 
389
  
390
  #Model assessment: RMSE and then krig the residuals....!
391
  
392
  res_mod_s<- data_s$dailyTmax - data_s[[pred_mod]]           #Residuals from kriging training
393
  res_mod_v<- data_v$dailyTmax - data_v[[pred_mod]]           #Residuals from kriging validation
394
  
395
  name2<-paste("res_mod",j,sep="")
396
  data_v[[name2]]<-as.numeric(res_mod_v)
397
  data_s[[name2]]<-as.numeric(res_mod_s)
398
  
399
  mod_obj<-vector("list",nmodels+2)  #This will contain the model objects fitting: 10/30
400
  mod_obj[[nmodels+1]]<-mod_kr_month  #Storing climatology object
401
  mod_obj[[nmodels+2]]<-mod_kr_day  #Storing delta object
402
  
403
  for (j in 1:nmodels){
404
    
405
    ##Model assessment: specific diagnostic/metrics for GAM
406
    
407
    name<-paste("mod",j,sep="")  #modj is the name of The "j" model (mod1 if j=1) 
408
    mod<-get(name)               #accessing GAM model ojbect "j"
409
    mod_obj[[j]]<-mod  #storing current model object
410
    
411
    #If mod "j" is not a model object
412
    if (inherits(mod,"try-error")) {
413
      results_AIC[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
414
      results_AIC[2]<- ns        #number of stations used in the training stage
415
      results_AIC[3]<- "AIC"
416
      results_AIC[j+3]<- NA
417
      
418
      results_GCV[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
419
      results_GCV[2]<- ns        #number of stations used in the training 
420
      results_GCV[3]<- "GCV"
421
      results_GCV[j+3]<- NA
422
      
423
      results_DEV[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
424
      results_DEV[2]<- ns        #number of stations used in the training stage
425
      results_DEV[3]<- "DEV"
426
      results_DEV[j+3]<- NA
427
      
428
      results_RMSE_f[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
429
      results_RMSE_f[2]<- ns        #number of stations used in the training stage
430
      results_RMSE_f[3]<- "RSME_f"
431
      results_RMSE_f[j+3]<- NA
432
      
433
      results_MAE_f[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
434
      results_MAE_f[2]<- ns        #number of stations used in the training stage
435
      results_MAE_f[3]<- "MAE_f"
436
      results_MAE_f[j+3]<-NA
437
      
438
      results_RMSE[1]<- sampling_dat$date[i]    #storing the interpolation dates in the first column
439
      results_RMSE[2]<- ns          #number of stations used in the training stage
440
      results_RMSE[3]<- "RMSE"
441
      results_RMSE[j+3]<- NA  #Storing RMSE for the model j
442
      results_MAE[1]<- sampling_dat$date[i]     #storing the interpolation dates in the first column
443
      results_MAE[2]<- ns           #number of stations used in the training stage
444
      results_MAE[3]<- "MAE"
445
      results_MAE[j+3]<- NA    #Storing MAE for the model j
446
      results_ME[1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
447
      results_ME[2]<- ns            #number of stations used in the training stage
448
      results_ME[3]<- "ME"
449
      results_ME[j+3]<- NA      #Storing ME for the model j
450
      results_R2[1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
451
      results_R2[2]<- ns            #number of stations used in the training stage
452
      results_R2[3]<- "R2"
453
      
454
      
455
      results_R2[j+3]<- NA      #Storing R2 for the model j
456
      
457
    }
458
    
459
    #If mod is a modelobject
460
    
461
    #If mod "j" is not a model object
462
    if (inherits(mod,"gam")) {
463
      
464
      results_AIC[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
465
      results_AIC[2]<- ns        #number of stations used in the training stage
466
      results_AIC[3]<- "AIC"
467
      results_AIC[j+3]<- AIC (mod)
468
      
469
      results_GCV[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
470
      results_GCV[2]<- ns        #number of stations used in the training 
471
      results_GCV[3]<- "GCV"
472
      results_GCV[j+3]<- mod$gcv.ubre
473
      
474
      results_DEV[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
475
      results_DEV[2]<- ns        #number of stations used in the training stage
476
      results_DEV[3]<- "DEV"
477
      results_DEV[j+3]<- mod$deviance
478
      
479
      y_var_fit= mod$fit
480
    
481
      results_RMSE_f[1]<- sampling_dat$date[i]  #storing the interpolation dates in the first column
482
      results_RMSE_f[2]<- ns        #number of stations used in the training stage
483
      results_RMSE_f[3]<- "RSME_f"
484
      #results_RMSE_f[j+3]<- sqrt(sum((y_var_fit-data_s$y_var)^2)/ns)
485
      results_RMSE_f[j+3]<-sqrt(mean(mod$residuals^2,na.rm=TRUE))
486
      
487
      results_MAE_f[1]<- sampling_dat$date[i]  #storing the interpolation sampling_dat$date in the first column
488
      results_MAE_f[2]<- ns        #number of stations used in the training stage
489
      results_MAE_f[3]<- "MAE_f"
490
      #results_MAE_f[j+3]<-sum(abs(y_var_fit-data_s$y_var))/ns
491
      results_MAE_f[j+3]<-mean(abs(mod$residuals),na.rm=TRUE)
492
      
493
      ##Model assessment: general diagnostic/metrics
494
      ##validation: using the testing data
495
      if (predval==1) {
496
      
497
        ##Model assessment: specific diagnostic/metrics for GAM
498
        
499
        name<-paste("mod",j,sep="")  #modj is the name of The "j" model (mod1 if j=1) 
500
        mod<-get(name)               #accessing GAM model ojbect "j"
501
        
502
        s_sgdf<-as(s_raster,"SpatialGridDataFrame") #Conversion to spatial grid data frame
503
        
504
        rpred<- predict(mod, newdata=s_sgdf, se.fit = TRUE) #Using the coeff to predict new values.
505
        y_pred<-rpred$fit #rpred is a list with fit being and array
506
        raster_pred<-r1
507
        layerNames(raster_pred)<-"y_pred"
508
        values(raster_pred)<-as.numeric(y_pred)
509
        
510
        if (bias_prediction==1){
511
          data_name<-paste("predicted_mod",j,"_",sampling_dat$date[i],"_",sampling_dat$prop[i],
512
                           "_",sampling_dat$run_samp[i],sep="")
513
          raster_name<-paste("GAM_bias_",data_name,out_prefix,".rst", sep="")
514
          writeRaster(raster_pred, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
515
          bias_rast<-raster_pred
516
          
517
          raster_pred=themolst+daily_delta_rast-bias_rast #Final surface  as a raster layer...wiht daily surface calculated earlier...
518
          layerNames(raster_pred)<-"y_pred"
519
          #=themolst+daily_delta_rast-bias_rast #Final surface  as a raster layer...
520
          
521
          data_name<-paste("predicted_mod",j,"_",sampling_dat$date[i],"_",sampling_dat$prop[i],
522
                           "_",sampling_dat$run_samp[i],sep="")
523
          raster_name<-paste("GAM_bias_tmax_",data_name,out_prefix,".rst", sep="")
524
          writeRaster(raster_pred, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
525
          
526
        }
527
        
528
        if (bias_prediction==0){
529
          data_name<-paste("predicted_mod",j,"_",sampling_dat$date[i],"_",sampling_dat$prop[i],
530
                           "_",sampling_dat$run_samp[i],sep="")
531
          raster_name<-paste("GAM_",data_name,out_prefix,".rst", sep="")
532
          writeRaster(raster_pred, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
533
          #writeRaster(r2, filename=raster_name,overwrite=TRUE)  #Writing the data in a raster file format...(IDRISI)
534
          
535
        }
536
        
537
        
538
        pred_sgdf<-as(raster_pred,"SpatialGridDataFrame") #Conversion to spatial grid data frame
539
        #rpred_val_s <- overlay(raster_pred,data_s)             #This overlays the kriged surface tmax and the location of weather stations
540
        
541
        rpred_val_s <- overlay(pred_sgdf,data_s)             #This overlays the interpolated surface tmax and the location of weather stations
542
        rpred_val_v <- overlay(pred_sgdf,data_v)             #This overlays the interpolated surface tmax and the location of weather stations
543
        
544
        pred_mod<-paste("pred_mod",j,sep="")
545
        #Adding the results back into the original dataframes.
546
        data_s[[pred_mod]]<-rpred_val_s$y_pred
547
        
548
        data_v[[pred_mod]]<-rpred_val_v$y_pred  
549
        
550
        #Model assessment: RMSE and then krig the residuals....!
551
        
552
        res_mod_s<-data_s[[y_var_name]] - data_s[[pred_mod]] #residuals from modeling training
553
        res_mod_v<-data_v[[y_var_name]] - data_v[[pred_mod]] #residuals from modeling validation
554
        
555
      }
556
      
557
      if (predval==0) {
558
      
559
        y_mod<- predict(mod, newdata=data_v, se.fit = TRUE) #Using the coeff to predict new values.
560
        
561
        pred_mod<-paste("pred_mod",j,sep="")
562
        #Adding the results back into the original dataframes.
563
        data_s[[pred_mod]]<-as.numeric(mod$fit)
564
        data_v[[pred_mod]]<-as.numeric(y_mod$fit)
565
        
566
        #Model assessment: RMSE and then krig the residuals....!
567
        
568
        #res_mod_s<- data_s$y_var - data_s[[pred_mod]]           #Residuals from modeling training
569
        #res_mod_v<- data_v$y_var - data_v[[pred_mod]]           #Residuals from modeling validation
570
        res_mod_s<-data_s[[y_var_name]] - data_s[[pred_mod]]
571
        res_mod_v<-data_v[[y_var_name]] - data_v[[pred_mod]]
572
        
573
      }
574

    
575
      ####ADDED ON JULY 20th
576
      res_mod<-res_mod_v
577
      
578
      #RMSE_mod <- sqrt(sum(res_mod^2)/nv)                 #RMSE FOR REGRESSION STEP 1: GAM  
579
      RMSE_mod<- sqrt(mean(res_mod^2,na.rm=TRUE))
580
      #MAE_mod<- sum(abs(res_mod),na.rm=TRUE)/(nv-sum(is.na(res_mod)))        #MAE from kriged surface validation
581
      MAE_mod<- mean(abs(res_mod), na.rm=TRUE)
582
      #ME_mod<- sum(res_mod,na.rm=TRUE)/(nv-sum(is.na(res_mod)))                    #ME, Mean Error or bias FOR REGRESSION STEP 1: GAM
583
      ME_mod<- mean(res_mod,na.rm=TRUE)                            #ME, Mean Error or bias FOR REGRESSION STEP 1: GAM
584
      #R2_mod<- cor(data_v$y_var,data_v[[pred_mod]])^2              #R2, coef. of var FOR REGRESSION STEP 1: GAM
585
      R2_mod<- cor(data_v$y_var,data_v[[pred_mod]], use="complete")^2
586
      results_RMSE[1]<- sampling_dat$date[i]    #storing the interpolation sampling_dat$date in the first column
587
      results_RMSE[2]<- ns          #number of stations used in the training stage
588
      results_RMSE[3]<- "RMSE"
589
      results_RMSE[j+3]<- RMSE_mod  #Storing RMSE for the model j
590
      results_MAE[1]<- sampling_dat$date[i]     #storing the interpolation dates in the first column
591
      results_MAE[2]<- ns           #number of stations used in the training stage
592
      results_MAE[3]<- "MAE"
593
      results_MAE[j+3]<- MAE_mod    #Storing MAE for the model j
594
      results_ME[1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
595
      results_ME[2]<- ns            #number of stations used in the training stage
596
      results_ME[3]<- "ME"
597
      results_ME[j+3]<- ME_mod      #Storing ME for the model j
598
      results_R2[1]<- sampling_dat$date[i]      #storing the interpolation dates in the first column
599
      results_R2[2]<- ns            #number of stations used in the training stage
600
      results_R2[3]<- "R2"
601
      results_R2[j+3]<- R2_mod      #Storing R2 for the model j
602
      
603
      #Saving residuals and prediction in the dataframes: tmax predicted from GAM
604

    
605
      name2<-paste("res_mod",j,sep="")
606
      data_v[[name2]]<-as.numeric(res_mod_v)
607
      data_s[[name2]]<-as.numeric(res_mod_s)
608
      #end of loop calculating RMSE
609
    }
610
  }
611
  
612
  #if (i==length(dates)){
613
  
614
  #Specific diagnostic measures related to the testing datasets
615

    
616
  results_table_RMSE<-as.data.frame(results_RMSE)
617
  results_table_MAE<-as.data.frame(results_MAE)
618
  results_table_ME<-as.data.frame(results_ME)
619
  results_table_R2<-as.data.frame(results_R2)
620
  results_table_RMSE_f<-as.data.frame(results_RMSE_f)
621
  results_table_MAE_f<-as.data.frame(results_MAE_f)
622
  
623
  results_table_AIC<-as.data.frame(results_AIC)
624
  results_table_GCV<-as.data.frame(results_GCV)
625
  results_table_DEV<-as.data.frame(results_DEV)
626
  
627
  tb_metrics1<-rbind(results_table_RMSE,results_table_MAE, results_table_ME, results_table_R2,results_table_RMSE_f,results_table_MAE_f)   #
628
  tb_metrics2<-rbind(results_table_AIC,results_table_GCV, results_table_DEV)
629
  
630
  #Preparing labels 10/30
631
  mod_labels<-rep("mod",nmodels+1)
632
  index<-as.character(1:(nmodels+1))
633
  mod_labels<-paste(mod_labels,index,sep="")
634
  cname<-c("dates","ns","metric", mod_labels)
635
  #cname<-c("dates","ns","metric","mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7","mod8","mod9")
636
  colnames(tb_metrics1)<-cname
637
  #cname<-c("dates","ns","metric","mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7","mod8")
638
  #colnames(tb_metrics2)<-cname
639
  colnames(tb_metrics2)<-cname[1:(nmodels+3)]
640
  
641
  #write.table(tb_diagnostic1, file= paste(path,"/","results_fusion_Assessment_measure1",out_prefix,".txt",sep=""), sep=",")
642
  
643
  #}  
644
  print(paste(sampling_dat$date[i],"processed"))
645
  # end of the for loop1
646
  #mod_obj<-list(mod1,mod2,mod3,mod4,mod5,mod6,mod7,mod8,mod9a,mod9b)
647
  #names(mod_obj)<-c("mod1","mod2","mod3","mod4","mod5","mod6","mod7","mod8","mod9a","mod9b")
648
  mod_labels_kr<-c("mod_kr_month", "mod_kr_day")
649
  names(mod_obj)<-c(mod_labels[1:nmodels],mod_labels_kr)
650
  results_list<-list(data_s,data_v,tb_metrics1,tb_metrics2,mod_obj,data_month,list_formulas)
651
  names(results_list)<-c("data_s","data_v","tb_metrics1","tb_metrics2","mod_obj","data_month","formulas")
652
  
653
  #results_list<-list(data_s,data_v,tb_metrics1,tb_metrics2)
654
  #results_list<-list(data_s,data_v,tb_metrics1,tb_metrics2,mod_obj,sampling_dat[i,],data_month)
655
  #names(results_list)<-c("data_s","data_v","tb_metrics1","tb_metrics2","mod_obj","sampling_dat","data_month")
656
  save(results_list,file= paste(path,"/","results_list_metrics_objects_",sampling_dat$date[i],"_",sampling_dat$prop[i],
657
                                "_",sampling_dat$run_samp[i],out_prefix,".RData",sep=""))
658
  return(results_list)
659
  #return(tb_diagnostic1)
660
}
(10-10/35)