Project

General

Profile

Download (14.5 KB) Statistics
| Branch: | Revision:
1
##################    MULTI SAMPLING GAM FUSION METHOD ASSESSMENT   ####################################
2
############################ Merging LST and station data ##########################################
3
#This script interpolates tmax values using MODIS LST and GHCND station data                      
4
#interpolation area. It requires the text file of stations and a shape file of the study area.           
5
#Note that the projection for both GHCND and study area is lonlat WGS84.       
6
#Options to run this program are:
7
#1) Multisampling: vary the porportions of hold out and use random samples for each run
8
#2)Constant sampling: use the same sample over the runs
9
#3)over dates: run over for example 365 dates without mulitsampling
10
#4)use seed number: use seed if random samples must be repeatable
11
#5)GAM fusion: possibilty of running GAM+FUSION or GAM+CAI and other options added
12
#The interpolation is done first at the monthly time scale then delta surfaces are added.
13
#AUTHOR: Benoit Parmentier                                                                        
14
#DATE: 02/26/2013                                                                                 
15
#PROJECT: NCEAS INPLANT: Environment and Organisms --TASK#568--                                   
16
###################################################################################################
17

    
18
###Loading R library and packages                                                      
19
library(gtools)                                         # loading some useful tools 
20
library(mgcv)                                           # GAM package by Simon Wood
21
library(sp)                                             # Spatial pacakge with class definition by Bivand et al.
22
library(spdep)                               # Spatial pacakge with methods and spatial stat. by Bivand et al.
23
library(rgdal)                               # GDAL wrapper for R, spatial utilities
24
library(gstat)                               # Kriging and co-kriging by Pebesma et al.
25
library(fields)                             # NCAR Spatial Interpolation methods such as kriging, splines
26
library(raster)                              # Hijmans et al. package for raster processing
27
library(rasterVis)
28
library(parallel)                            # Urbanek S. and Ripley B., package for multi cores & parralel processing
29
library(reshape)
30
library(plotrix)
31
library(maptools)
32

    
33
### Parameters and argument
34

    
35
infile2<-"list_365_dates_04212012.txt"
36

    
37
## output param from previous script: Database_stations_covariates_processing_function
38
infile_monthly<-"monthly_covariates_ghcn_data_TMAXy2010_2010_VE_02082013.shp"
39
infile_daily<-"daily_covariates_ghcn_data_TMAXy2010_2010_VE_02082013.shp"
40
infile_locs<-"stations_venezuela_region_y2010_2010_VE_02082013.shp"
41
infile3<-"covariates__venezuela_region__VE_01292013.tif" #this is an output from covariate script
42
var<-"TMAX"
43
out_prefix<-"_365d_GAM_fus5_all_lstd_02202013"                #User defined output prefix
44
CRS_locs_WGS84<-CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +towgs84=0,0,0") #Station coords WGS84: same as earlier
45
#CRS_interp<-"+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";
46
#infile_monthly<-"monthly_covariates_ghcn_data_TMAXy2010_2010_VE_02082013.shp" #outile4 from database_covar script
47
#infile_daily<-"daily_covariates_ghcn_data_TMAXy2010_2010_VE_02082013.shp"  #outfile3 from database_covar script
48
#infile_locs<-"stations_venezuela_region_y2010_2010_VE_02082013.shp" #outfile2? from database covar script
49

    
50
###
51

    
52
if (var=="TMAX"){
53
  y_var_name<-"dailyTmax"                                       
54
}
55
if (var=="TMIN"){
56
  y_var_name<-"dailyTmin"                                       
57
}
58

    
59
#Input for sampling function...
60
seed_number<- 100  #if seed zero then no seed?     
61
nb_sample<-1           #number of time random sampling must be repeated for every hold out proportion
62
prop_min<-0.3          #if prop_min=prop_max and step=0 then predicitons are done for the number of dates...
63
prop_max<-0.3
64
step<-0         
65
constant<-0             #if value 1 then use the same samples as date one for the all set of dates
66

    
67
#Models to run...this can be change for each run
68
list_models<-c("y_var ~ s(elev_1)",
69
               "y_var ~ s(LST)",
70
               "y_var ~ s(elev_1,LST)",
71
               "y_var ~ s(lat) + s(lon)+ s(elev_1)",
72
               "y_var ~ s(lat,lon,elev_1)",
73
               "y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST)", 
74
               "y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST) + s(LC2)",
75
               "y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST) + s(LC6)", 
76
               "y_var ~ s(lat,lon) + s(elev_1) + s(N_w,E_w) + s(LST) + s(DISTOC)")
77

    
78
#Choose interpolation method...
79
interpolation_method<-c("gam_fusion","gam_CAI") #other otpions to be added later
80

    
81
#Default name of LST avg to be matched               
82
lst_avg<-c("mm_01","mm_02","mm_03","mm_04","mm_05","mm_06","mm_07","mm_08","mm_09","mm_10","mm_11","mm_12")  
83

    
84
in_path<-"/home/parmentier/Data/IPLANT_project/Venezuela_interpolation/Venezuela_01142013/input_data"
85
#Create on the fly output folder...
86
out_path<-"/home/parmentier/Data/IPLANT_project/Venezuela_interpolation/Venezuela_01142013/output_data"
87
script_path<-"/home/parmentier/Data/IPLANT_project/Venezuela_interpolation/Venezuela_01142013/"
88
setwd(in_path)
89

    
90
source(file.path(script_path,"GAM_fusion_function_multisampling_02262013.R"))
91
source(file.path(script_path,"GAM_fusion_function_multisampling_validation_metrics_02262013.R"))
92

    
93
###################### START OF THE SCRIPT ########################
94

    
95
################# CREATE LOG FILE #####################
96

    
97
#create log file to keep track of details such as processing times and parameters.
98

    
99
log_fname<-paste("R_log_t",out_prefix, ".log",sep="")
100

    
101
if (file.exists(log_fname)){  #Stop the script???
102
  file.remove(log_fname)
103
  log_file<-file(log_fname,"w")
104
}
105
if (!file.exists(log_fname)){
106
  log_file<-file(log_fname,"w")
107
}
108

    
109
time1<-proc.time()    #Start stop watch
110
writeLines(paste("Starting script at this local Date and Time: ",as.character(Sys.time()),sep=""),
111
           con=log_file,sep="\n")
112
writeLines("Starting script process time:",con=log_file,sep="\n")
113
writeLines(as.character(time1),con=log_file,sep="\n")    
114

    
115
############### Reading the daily station data and other data #################
116

    
117
ghcn<-readOGR(dsn=in_path,layer=sub(".shp","",infile_daily))
118
CRS_interp<-proj4string(ghcn)                       #Storing projection information (ellipsoid, datum,etc.)
119
stat_loc<-readOGR(dsn=in_path,layer=sub(".shp","",infile_locs))
120
dates <-readLines(file.path(in_path,infile2)) #dates to be predicted
121

    
122
#Reading of covariate brick covariates can be changed...
123
rnames <-c("x","y","lon","lat","N","E","N_w","E_w","elev","slope","aspect","CANHEIGHT","DISTOC")
124
lc_names<-c("LC1","LC2","LC3","LC4","LC5","LC6","LC7","LC8","LC9","LC10","LC11","LC12")
125
lst_names<-c("mm_01","mm_02","mm_03","mm_04","mm_05","mm_06","mm_07","mm_08","mm_09","mm_10","mm_11","mm_12",
126
                    "nobs_01","nobs_02","nobs_03","nobs_04","nobs_05","nobs_06","nobs_07","nobs_08",
127
                    "nobs_09","nobs_10","nobs_11","nobs_12")                  
128
covar_names<-c(rnames,lc_names,lst_names)                
129
s_raster<-brick(infile3)                   #read in the data brck
130
names(s_raster)<-covar_names               #Assigning names to the raster layers: making sure it is included in the extraction
131

    
132
#Reading monthly data
133
data3<-readOGR(dsn=in_path,layer=sub(".shp","",infile_monthly))
134
dst_all<-data3
135
dst<-data3
136

    
137
### TO DO -important ###
138
#Cleaning/sceerniging functions for daily stations, monthly stations and covariates?? do this at the preparation stage!!!
139
##
140

    
141
##### Create sampling: select training and testing sites ###
142
#Make this a a function!!!!
143
                  
144
if (seed_number>0) {
145
  set.seed(seed_number)                        #Using a seed number allow results based on random number to be compared...
146
}
147
nel<-length(dates)
148
dates_list<-vector("list",nel) #list of one row data.frame
149

    
150
prop_range<-(seq(from=prop_min,to=prop_max,by=step))*100     #range of proportion to run
151
sn<-length(dates)*nb_sample*length(prop_range)               #Number of samples to run
152

    
153
for(i in 1:length(dates)){
154
  d_tmp<-rep(dates[i],nb_sample*length(prop_range)) #repeating same date
155
  s_nb<-rep(1:nb_sample,length(prop_range))         #number of random sample per proportion
156
  prop_tmp<-sort(rep(prop_range, nb_sample))
157
  tab_run_tmp<-cbind(d_tmp,s_nb,prop_tmp)
158
  dates_list[[i]]<-tab_run_tmp
159
}
160

    
161
sampling_dat<-as.data.frame(do.call(rbind,dates_list))
162
names(sampling_dat)<-c("date","run_samp","prop")
163

    
164
for(i in 2:3){            # start of the for loop #1
165
  sampling_dat[,i]<-as.numeric(as.character(sampling_dat[,i]))  
166
}
167

    
168
sampling_dat$date<- as.character(sampling_dat[,1])
169
#ghcn.subsets <-lapply(dates, function(d) subset(ghcn, date==d)) #this creates a list of 10 or 365 subsets dataset based on dates
170
ghcn.subsets <-lapply(as.character(sampling_dat$date), function(d) subset(ghcn, date==d)) #this creates a list of 10 or 365 subsets dataset based on dates
171

    
172
#Make this a function??
173
## adding choice of constant sample 
174
if (seed_number>0) {
175
  set.seed(seed_number)                        #Using a seed number allow results based on random number to be compared...
176
}
177

    
178
sampling<-vector("list",length(ghcn.subsets))
179
sampling_station_id<-vector("list",length(ghcn.subsets))
180
for(i in 1:length(ghcn.subsets)){
181
  n<-nrow(ghcn.subsets[[i]])
182
  prop<-(sampling_dat$prop[i])/100
183
  ns<-n-round(n*prop)   #Create a sample from the data frame with 70% of the rows
184
  nv<-n-ns              #create a sample for validation with prop of the rows
185
  ind.training <- sample(nrow(ghcn.subsets[[i]]), size=ns, replace=FALSE) #This selects the index position for 70% of the rows taken randomly
186
  ind.testing <- setdiff(1:nrow(ghcn.subsets[[i]]), ind.training)
187
  #Find the corresponding 
188
  data_sampled<-ghcn.subsets[[i]][ind.training,] #selected the randomly sampled stations
189
  station_id.training<-data_sampled$station     #selected id for the randomly sampled stations (115)
190
  #Save the information
191
  sampling[[i]]<-ind.training
192
  sampling_station_id[[i]]<- station_id.training
193
}
194
## Use same samples across the year...
195
if (constant==1){
196
  sampled<-sampling[[1]]
197
  data_sampled<-ghcn.subsets[[1]][sampled,] #selected the randomly sampled stations
198
  station_sampled<-data_sampled$station     #selected id for the randomly sampled stations (115)
199
  list_const_sampling<-vector("list",sn)
200
  list_const_sampling_station_id<-vector("list",sn)
201
  for(i in 1:sn){
202
    station_id.training<-intersect(station_sampled,ghcn.subsets[[i]]$station)
203
    ind.training<-match(station_id.training,ghcn.subsets[[i]]$station)
204
    list_const_sampling[[i]]<-ind.training
205
    list_const_sampling_station_id[[i]]<-station_id.training
206
  }
207
  sampling<-list_const_sampling 
208
  sampling_station_id<-list_const_sampling_station_id
209
}
210
#return()
211

    
212
########### PREDICT FOR MONTHLY SCALE  #############
213

    
214
#First predict at the monthly time scale: climatology
215
writeLines("Predictions at monthly scale:",con=log_file,sep="\n")
216
t1<-proc.time()
217
gamclim_fus_mod<-mclapply(1:12, runClim_KGFusion,mc.preschedule=FALSE,mc.cores = 6) #This is the end bracket from mclapply(...) statement
218
#gamclim_fus_mod<-mclapply(1:12, runClim_KGFusion,mc.preschedule=FALSE,mc.cores = 4) #This is the end bracket from mclapply(...) statement
219
save(gamclim_fus_mod,file= paste("gamclim_fus_mod",out_prefix,".RData",sep=""))
220
t2<-proc.time()-t1
221
writeLines(as.character(t2),con=log_file,sep="\n")
222

    
223
#now get list of raster clim layers
224

    
225
list_tmp<-vector("list",length(gamclim_fus_mod))
226
for (i in 1:length(gamclim_fus_mod)){
227
  tmp<-gamclim_fus_mod[[i]]$clim
228
  list_tmp[[i]]<-tmp
229
}
230

    
231
################## PREDICT AT DAILY TIME SCALE #################
232

    
233
#put together list of clim models per month...
234
rast_clim_yearlist<-list_tmp
235
#Second predict at the daily time scale: delta
236

    
237
#gam_fus_mod<-mclapply(1:1, runGAMFusion,mc.preschedule=FALSE,mc.cores = 1) #This is the end bracket from mclapply(...) statement
238
writeLines("Predictions at the daily scale:",con=log_file,sep="\n")
239
t1<-proc.time()
240
gam_fus_mod<-mclapply(1:length(ghcn.subsets), runGAMFusion,mc.preschedule=FALSE,mc.cores = 9) #This is the end bracket from mclapply(...) statement
241
save(gam_fus_mod,file= paste("gam_fus_mod",out_prefix,".RData",sep=""))
242
t2<-proc.time()-t1
243
writeLines(as.character(t2),con=log_file,sep="\n")
244

    
245
############### NOW RUN VALIDATION #########################
246

    
247
list_tmp<-vector("list",length(gam_fus_mod))
248
for (i in 1:length(gam_fus_mod)){
249
  tmp<-gam_fus_mod[[i]][[y_var_name]]  #y_var_name is the variable predicted (tmax or tmin)
250
  list_tmp[[i]]<-tmp
251
}
252
rast_day_yearlist<-list_tmp #list of predicted images
253

    
254
writeLines("Validation step:",con=log_file,sep="\n")
255
t1<-proc.time()
256
#calculate_accuary_metrics<-function(i)
257
gam_fus_validation_mod<-mclapply(1:length(gam_fus_mod), calculate_accuracy_metrics,mc.preschedule=FALSE,mc.cores = 9) #This is the end bracket from mclapply(...) statement
258
#gam_fus_validation_mod<-mclapply(1:1, calculate_accuracy_metrics,mc.preschedule=FALSE,mc.cores = 1) #This is the end bracket from mclapply(...) statement
259
save(gam_fus_validation_mod,file= paste("gam_fus_validation_mod",out_prefix,".RData",sep=""))
260
t2<-proc.time()-t1
261
writeLines(as.character(t2),con=log_file,sep="\n")
262

    
263
#################### ASSESSMENT OF PREDICTIONS: PLOTS OF ACCURACY METRICS ###########
264

    
265
##Create data.frame with valiation metrics for a full year
266
tb_diagnostic_v<-extract_from_list_obj(gam_fus_validation_mod,"metrics_v")
267
rownames(tb_diagnostic_v)<-NULL #remove row names
268

    
269
#Call function to create plots of metrics for validation dataset
270
metric_names<-c("rmse","mae","me","r","m50")
271
summary_metrics<-boxplot_from_tb(tb_diagnostic_v,metric_names,out_prefix)
272
names(summary_metrics)<-c("avg","median")
273
##Write out information concerning accuracy and predictions
274
outfile<-file.path(in_path,paste("assessment_measures_",out_prefix,".txt",sep=""))
275
write.table(tb_diagnostic_v,file= outfile,row.names=FALSE,sep=",")
276
write.table(summary_metrics[[1]], file= outfile, append=TRUE,sep=",") #write out avg
277
write.table(summary_metrics[[2]], file= outfile, append=TRUE,sep=",") #write out median
278

    
279
#################### CLOSE LOG FILE  #############
280

    
281
#close log_file connection and add meta data
282
writeLines("Finished script process time:",con=log_file,sep="\n")
283
time2<-proc.time()-time1
284
writeLines(as.character(time2),con=log_file,sep="\n")
285
#later on add all the paramters used in the script...
286
writeLines(paste("Finished script at this local Date and Time: ",as.character(Sys.time()),sep=""),
287
           con=log_file,sep="\n")
288
writeLines("End of script",con=log_file,sep="\n")
289
close(log_file)
290

    
291
############################################################
292
######################## END OF SCRIPT #####################
(9-9/37)