Project

General

Profile

Download (18.6 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 separately 
12
#AUTHOR: Benoit Parmentier                                                                        
13
#DATE: 10/27/2012                                                                                 
14
#PROJECT: NCEAS INPLANT: Environment and Organisms --TASK#363--                                   
15
###################################################################################################
16

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

    
32
infile1<- "ghcn_or_tmax_covariates_06262012_OR83M.shp"             #GHCN shapefile containing variables for modeling 2010                 
33
infile2<-"list_365_dates_04212012.txt"
34
infile3<-"LST_dates_var_names.txt"                        #LST dates name
35
infile4<-"models_interpolation_05142012.txt"              #Interpolation model names
36
infile5<-"mean_day244_rescaled.rst"                       #Raster or grid for the locations of predictions
37
#infile6<-"lst_climatology.txt"
38
infile6<-"LST_files_monthly_climatology.txt"
39
inlistf<-"list_files_05032012.txt"                        #Stack of images containing the Covariates
40

    
41
path<-"/home/parmentier/Data/IPLANT_project/data_Oregon_stations_10242012_GAM"
42

    
43
setwd(path)
44
#Station location of the study area
45
stat_loc<-read.table(paste(path,"/","location_study_area_OR_0602012.txt",sep=""),sep=",", header=TRUE)
46
#GHCN Database for 1980-2010 for study area (OR) 
47
data3<-read.table(paste(path,"/","ghcn_data_TMAXy1980_2010_OR_0602012.txt",sep=""),sep=",", header=TRUE)
48

    
49
nmodels<-8   #number of models running
50
y_var_name<-"dailyTmax"
51
predval<-1
52
prop<-0.3             #Proportion of testing retained for validation   
53
#prop<-0.25
54
seed_number<- 100  #if seed zero then no seed?                                                                 #Seed number for random sampling
55
out_prefix<-"_365d_GAM_fusion_const_all_lstd_10282012"                #User defined output prefix
56

    
57
bias_val<-0            #if value 1 then training data is used in the bias surface rather than the all monthly stations
58
bias_prediction<-1     #if value 1 then use GAM for the BIAS prediction otherwise GAM direct repdiction for y_var (daily tmax)
59
nb_sample<-1           #number of time random sampling must be repeated for every hold out proportion
60
prop_min<-0.3          #if prop_min=prop_max and step=0 then predicitons are done for the number of dates...
61
prop_max<-0.3
62
step<-0         
63
constant<-1             #if value 1 then use the same samples as date one for the all set of dates
64
#projection used in the interpolation of the study area
65
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";
66
CRS_locs_WGS84<-CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +towgs84=0,0,0") #Station coords WGS84
67

    
68
source("GAM_fusion_function_multisampling_10272012.R")
69

    
70
###################### START OF THE SCRIPT ########################
71

    
72
###Reading the station data and setting up for models' comparison
73
filename<-sub(".shp","",infile1)             #Removing the extension from file.
74
ghcn<-readOGR(".", filename)                 #reading shapefile 
75

    
76
CRS<-proj4string(ghcn)                       #Storing projection information (ellipsoid, datum,etc.)
77

    
78
mean_LST<- readGDAL(infile5)                 #Reading the whole raster in memory. This provides a grid for kriging
79
proj4string(mean_LST)<-CRS                   #Assigning coordinate information to prediction grid.
80

    
81
ghcn <- transform(ghcn,Northness = cos(ASPECT*pi/180)) #Adding a variable to the dataframe
82
ghcn <- transform(ghcn,Eastness = sin(ASPECT*pi/180))  #adding variable to the dataframe.
83
ghcn <- transform(ghcn,Northness_w = sin(slope*pi/180)*cos(ASPECT*pi/180)) #Adding a variable to the dataframe
84
ghcn <- transform(ghcn,Eastness_w = sin(slope*pi/180)*sin(ASPECT*pi/180))  #adding variable to the dataframe.
85

    
86
#Remove NA for LC and CANHEIGHT
87
ghcn$LC1[is.na(ghcn$LC1)]<-0
88
ghcn$LC3[is.na(ghcn$LC3)]<-0
89
ghcn$CANHEIGHT[is.na(ghcn$CANHEIGHT)]<-0
90

    
91
dates <-readLines(paste(path,"/",infile2, sep=""))
92
LST_dates <-readLines(paste(path,"/",infile3, sep=""))
93
models <-readLines(paste(path,"/",infile4, sep=""))
94

    
95
##Extracting the variables values from the raster files                                             
96

    
97
lines<-read.table(paste(path,"/",inlistf,sep=""), sep=" ")                  #Column 1 contains the names of raster files
98
inlistvar<-lines[,1]
99
inlistvar<-paste(path,"/",as.character(inlistvar),sep="")
100
covar_names<-as.character(lines[,2])                                         #Column two contains short names for covaraites
101

    
102
s_raster<- stack(inlistvar)                                                  #Creating a stack of raster images from the list of variables.
103
layerNames(s_raster)<-covar_names                                            #Assigning names to the raster layers
104
projection(s_raster)<-CRS
105

    
106
#stat_val<- extract(s_raster, ghcn3)                                          #Extracting values from the raster stack for every point location in coords data frame.
107
pos<-match("ASPECT",layerNames(s_raster)) #Find column with name "value"
108
r1<-raster(s_raster,layer=pos)             #Select layer from stack
109
pos<-match("slope",layerNames(s_raster)) #Find column with name "value"
110
r2<-raster(s_raster,layer=pos)             #Select layer from stack
111
N<-cos(r1*pi/180)
112
E<-sin(r1*pi/180)
113
Nw<-sin(r2*pi/180)*cos(r1*pi/180)   #Adding a variable to the dataframe
114
Ew<-sin(r2*pi/180)*sin(r1*pi/180)   #Adding variable to the dataframe.
115

    
116
pos<-match("LC1",layerNames(s_raster)) #Find column with name "value"
117
LC1<-raster(s_raster,layer=pos)             #Select layer from stack
118
s_raster<-dropLayer(s_raster,pos)
119
LC1[is.na(LC1)]<-0
120

    
121
pos<-match("LC3",layerNames(s_raster)) #Find column with name "value"
122
LC3<-raster(s_raster,layer=pos)             #Select layer from stack
123
s_raster<-dropLayer(s_raster,pos)
124
LC3[is.na(LC3)]<-0
125

    
126
pos<-match("LC4",layerNames(s_raster)) #Find column with name "value"
127
LC4<-raster(s_raster,layer=pos)             #Select layer from stack
128
s_raster<-dropLayer(s_raster,pos)
129
LC4[is.na(LC4)]<-0
130

    
131
pos<-match("LC6",layerNames(s_raster)) #Find column with name "value"
132
LC6<-raster(s_raster,layer=pos)             #Select layer from stack
133
s_raster<-dropLayer(s_raster,pos)
134
LC6[is.na(LC6)]<-0
135

    
136
LC_s<-stack(LC1,LC3,LC4,LC6)
137
layerNames(LC_s)<-c("LC1_forest","LC3_grass","LC4_crop","LC6_urban")
138
plot(LC_s)
139

    
140
pos<-match("CANHEIGHT",layerNames(s_raster)) #Find column with name "value"
141
CANHEIGHT<-raster(s_raster,layer=pos)             #Select layer from stack
142
s_raster<-dropLayer(s_raster,pos)
143
CANHEIGHT[is.na(CANHEIGHT)]<-0
144

    
145
xy<-coordinates(r1)  #get x and y projected coordinates...
146
xy_latlon<-project(xy, CRS, inv=TRUE) # find lat long for projected coordinats (or pixels...)
147
lon<-raster(xy_latlon) #Transform a matrix into a raster object ncol=ncol(r1), nrow=nrow(r1))
148
ncol(lon)<-ncol(r1)
149
nrow(lon)<-nrow(r1)
150
extent(lon)<-extent(r1)
151
projection(lon)<-CRS  #At this stage this is still an empty raster with 536 nrow and 745 ncell 
152
lat<-lon
153
values(lon)<-xy_latlon[,1]
154
values(lat)<-xy_latlon[,2]
155

    
156
r<-stack(N,E,Nw,Ew,lon,lat,LC1,LC3,LC4,LC6, CANHEIGHT)
157
rnames<-c("Northness","Eastness","Northness_w","Eastness_w", "lon","lat","LC1","LC3","LC4","LC6","CANHEIGHT")
158
layerNames(r)<-rnames
159
s_raster<-addLayer(s_raster, r)
160

    
161
#s_sgdf<-as(s_raster,"SpatialGridDataFrame") #Conversion to spatial grid data frame
162

    
163
####### Preparing LST stack of climatology...
164

    
165
#l=list.files(pattern="mean_month.*rescaled.rst")
166
l <-readLines(paste(path,"/",infile6, sep=""))
167
molst<-stack(l)  #Creating a raster stack...
168
#setwd(old)
169
molst<-molst-273.16  #K->C          #LST stack of monthly average...
170
idx <- seq(as.Date('2010-01-15'), as.Date('2010-12-15'), 'month')
171
molst <- setZ(molst, idx)
172
layerNames(molst) <- month.abb
173

    
174

    
175
######  Preparing tables for model assessment: specific diagnostic/metrics
176

    
177
#Model assessment: specific diagnostics/metrics
178
results_AIC<- matrix(1,1,nmodels+3)  
179
results_GCV<- matrix(1,1,nmodels+3)
180
results_DEV<- matrix(1,1,nmodels+3)
181
#results_RMSE_f<- matrix(1,length(models)+3)
182

    
183
#Model assessment: general diagnostic/metrics 
184
results_RMSE <- matrix(1,1,nmodels+4)
185
results_MAE <- matrix(1,1,nmodels+4)
186
results_ME <- matrix(1,1,nmodels+4)       #There are 8+1 models
187
results_R2 <- matrix(1,1,nmodels+4)       #Coef. of determination for the validation dataset
188

    
189
results_RMSE_f<- matrix(1,1,nmodels+4)    #RMSE fit, RMSE for the training dataset
190
results_MAE_f <- matrix(1,1,nmodels+4)
191

    
192
######## Preparing monthly averages from the ProstGres database and extracting covarvariates from stack
193

    
194
# do this work outside of (before) this function
195
# to avoid making a copy of the data frame inside the function call
196
date1<-ISOdate(data3$year,data3$month,data3$day) #Creating a date object from 3 separate column
197
date2<-as.POSIXlt(as.Date(date1))
198
data3$date<-date2
199
d<-subset(data3,year>=2000 & mflag=="0" ) #Selecting dataset 2000-2010 with good quality: 193 stations
200
#May need some screeing??? i.e. range of temp and elevation...
201
d1<-aggregate(value~station+month, data=d, mean)  #Calculate monthly mean for every station in OR
202
id<-as.data.frame(unique(d1$station))     #Unique station in OR for year 2000-2010: 193 but 7 loss of monthly avg    
203

    
204
dst<-merge(d1, stat_loc, by.x="station", by.y="STAT_ID")   #Inner join all columns are retained
205

    
206
#This allows to change only one name of the data.frame
207
pos<-match("value",names(dst)) #Find column with name "value"
208
names(dst)[pos]<-c("TMax")
209
dst$TMax<-dst$TMax/10                #TMax is the average max temp for monthy data
210
#dstjan=dst[dst$month==9,]  #dst contains the monthly averages for tmax for every station over 2000-2010
211

    
212
#Extracting covariates from stack
213
coords<- dst[c('lon','lat')]              #Define coordinates in a data frame
214
coordinates(dst)<-coords                      #Assign coordinates to the data frame
215
proj4string(dst)<-CRS_locs_WGS84                  #Assign coordinates reference system in PROJ4 format
216
dst_month<-spTransform(dst,CRS(CRS_interp))     #Project from WGS84 to new coord. system
217

    
218
stations_val<-extract(s_raster,dst_month)  #extraction of the infomration at station location
219
stations_val<-as.data.frame(stations_val)
220
dst_extract<-cbind(dst_month,stations_val)
221
dst<-dst_extract
222

    
223
######### Preparing daily values for training and testing
224

    
225
#Screening for bad values: value is tmax in this case
226
#ghcn$value<-as.numeric(ghcn$value)
227
ghcn_all<-ghcn
228
ghcn_test<-subset(ghcn,ghcn$value>-150 & ghcn$value<400)
229
ghcn_test2<-subset(ghcn_test,ghcn_test$ELEV_SRTM>0)
230
ghcn<-ghcn_test2
231
#coords<- ghcn[,c('x_OR83M','y_OR83M')]
232

    
233
##Sampling: training and testing sites.
234

    
235
if (seed_number>0) {
236
  set.seed(seed_number)                        #Using a seed number allow results based on random number to be compared...
237
}
238
nel<-length(dates)
239
dates_list<-vector("list",nel) #list of one row data.frame
240

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

    
244
for(i in 1:length(dates)){
245
  d_tmp<-rep(dates[i],nb_sample*length(prop_range)) #repeating same date
246
  s_nb<-rep(1:nb_sample,length(prop_range))         #number of random sample per proportion
247
  prop_tmp<-sort(rep(prop_range, nb_sample))
248
  tab_run_tmp<-cbind(d_tmp,s_nb,prop_tmp)
249
  dates_list[[i]]<-tab_run_tmp
250
}
251

    
252
sampling_dat<-as.data.frame(do.call(rbind,dates_list))
253
names(sampling_dat)<-c("date","run_samp","prop")
254

    
255
for(i in 2:3){            # start of the for loop #1
256
  sampling_dat[,i]<-as.numeric(as.character(sampling_dat[,i]))  
257
}
258

    
259
sampling_dat$date<- as.character(sampling_dat[,1])
260
#ghcn.subsets <-lapply(dates, function(d) subset(ghcn, date==d)) #this creates a list of 10 or 365 subsets dataset based on dates
261
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
262

    
263
## adding choice of constant sample 
264
if (seed_number>0) {
265
  set.seed(seed_number)                        #Using a seed number allow results based on random number to be compared...
266
}
267

    
268
sampling<-vector("list",length(ghcn.subsets))
269
sampling_station_id<-vector("list",length(ghcn.subsets))
270
for(i in 1:length(ghcn.subsets)){
271
  n<-nrow(ghcn.subsets[[i]])
272
  prop<-(sampling_dat$prop[i])/100
273
  ns<-n-round(n*prop)   #Create a sample from the data frame with 70% of the rows
274
  nv<-n-ns              #create a sample for validation with prop of the rows
275
  ind.training <- sample(nrow(ghcn.subsets[[i]]), size=ns, replace=FALSE) #This selects the index position for 70% of the rows taken randomly
276
  ind.testing <- setdiff(1:nrow(ghcn.subsets[[i]]), ind.training)
277
  #Find the corresponding 
278
  data_sampled<-ghcn.subsets[[i]][ind.training,] #selected the randomly sampled stations
279
  station_id.training<-data_sampled$station     #selected id for the randomly sampled stations (115)
280
  #Save the information
281
  sampling[[i]]<-ind.training
282
  sampling_station_id[[i]]<- station_id.training
283
}
284
## Use same samples across the year...
285
if (constant==1){
286
  sampled<-sampling[[1]]
287
  data_sampled<-ghcn.subsets[[1]][sampled,] #selected the randomly sampled stations
288
  station_sampled<-data_sampled$station     #selected id for the randomly sampled stations (115)
289
  list_const_sampling<-vector("list",sn)
290
  list_const_sampling_station_id<-vector("list",sn)
291
  for(i in 1:sn){
292
    station_id.training<-intersect(station_sampled,ghcn.subsets[[i]]$station)
293
    ind.training<-match(station_id.training,ghcn.subsets[[i]]$station)
294
    list_const_sampling[[i]]<-ind.training
295
    list_const_sampling_station_id[[i]]<-station_id.training
296
  }
297
  sampling<-list_const_sampling 
298
  sampling_station_id<-list_const_sampling_station_id
299
}
300

    
301
# sampling<-vector("list",length(ghcn.subsets))
302
# 
303
# for(i in 1:length(ghcn.subsets)){
304
#   n<-nrow(ghcn.subsets[[i]])
305
#   prop<-(sampling_dat$prop[i])/100
306
#   ns<-n-round(n*prop)   #Create a sample from the data frame with 70% of the rows
307
#   nv<-n-ns              #create a sample for validation with prop of the rows
308
#   ind.training <- sample(nrow(ghcn.subsets[[i]]), size=ns, replace=FALSE) #This selects the index position for 70% of the rows taken randomly
309
#   ind.testing <- setdiff(1:nrow(ghcn.subsets[[i]]), ind.training)
310
#   sampling[[i]]<-ind.training
311
# }
312
# 
313
# if (constant==1){
314
#   sampled<-sampling[[1]]
315
#   list_const_sampling<-vector("list",sn)
316
#   for(i in 1:sn){
317
#     list_const_sampling[[i]]<-sampled
318
#   }
319
#   sampling<-list_const_sampling  
320
# }
321

    
322
######## Prediction for the range of dates and sampling data
323

    
324
#gam_fus_mod<-mclapply(1:length(dates), runGAMFusion,mc.preschedule=FALSE,mc.cores = 8) #This is the end bracket from mclapply(...) statement
325
#gam_fus_mod_s<-mclapply(1:1, runGAMFusion,mc.preschedule=FALSE,mc.cores = 1) #This is the end bracket from mclapply(...) statement
326
gam_fus_mod_s<-mclapply(1:length(ghcn.subsets), runGAMFusion,mc.preschedule=FALSE,mc.cores = 8) #This is the end bracket from mclapply(...) statement
327
#gam_fus_mod2<-mclapply(4:4, runGAMFusion,mc.preschedule=FALSE,mc.cores = 1) #This is the end bracket from mclapply(...) statement
328

    
329
save(gam_fus_mod_s,file= paste(path,"/","results2_fusion_Assessment_measure_all",out_prefix,".RData",sep=""))
330

    
331
## Plotting and saving diagnostic measures
332

    
333
tb<-gam_fus_mod_s[[1]][[3]][0,]  #empty data frame with metric table structure that can be used in rbinding...
334
tb_tmp<-gam_fus_mod_s #copy
335

    
336
for (i in 1:length(tb_tmp)){
337
  tmp<-tb_tmp[[i]][[3]]
338
  tb<-rbind(tb,tmp)
339
}
340
rm(tb_tmp)
341

    
342
for(i in 4:ncol(tb)){            # start of the for loop #1
343
  tb[,i]<-as.numeric(as.character(tb[,i]))  
344
}
345

    
346
metrics<-as.character(unique(tb$metric))            #Name of accuracy metrics (RMSE,MAE etc.)
347
tb_metric_list<-vector("list",length(metrics))
348

    
349
for(i in 1:length(metrics)){            # Reorganizing information in terms of metrics 
350
  metric_name<-paste("tb_",metrics[i],sep="")
351
  tb_metric<-subset(tb, metric==metrics[i])
352
  tb_metric<-cbind(tb_metric,sampling_dat[,2:3])
353
  assign(metric_name,tb_metric)
354
  tb_metric_list[[i]]<-tb_metric
355
}
356

    
357
tb_diagnostic<-do.call(rbind,tb_metric_list)
358
#tb_diagnostic[["prop"]]<-as.factor(tb_diagnostic[["prop"]])
359
sampling_obj<-list(sampling_dat=sampling_dat,training=sampling, training_id=sampling_station_id, tb=tb_diagnostic)
360

    
361
#write.table(avg_tb, file= paste(path,"/","results2_fusion_Assessment_measure_avg_",out_prefix,".txt",sep=""), sep=",")
362
#write.table(median_tb, file= paste(path,"/","results2_fusion_Assessment_measure_median_",out_prefix,".txt",sep=""), sep=",")
363
write.table(tb_diagnostic, file= paste(path,"/","results2_fusion_Assessment_measure",out_prefix,".txt",sep=""), sep=",")
364
write.table(tb, file= paste(path,"/","results2_fusion_Assessment_measure_all",out_prefix,".txt",sep=""), sep=",")
365
save(sampling_obj, file= paste(path,"/","results2_fusion_sampling_obj",out_prefix,".RData",sep=""))
366
save(gam_fus_mod_s,file= paste(path,"/","results2_fusion_Assessment_measure_all",out_prefix,".RData",sep=""))
367

    
368
## Summary of number of files and results
369
#l_f<-list.files(pattern="GAM_bias_tmax_predicted_mod1_20100103_30_1_365d_GAM_fusion_lstd_10062012.rst$")
370
#r6<-raster(l_f)
371
#plot(r6)
372
#results_list_metrics_objects_*_20101231_30_1_365d_GAM_fusion_lstd_10062012.RData
373
#l_f<-list.files(pattern=paste(".*","tmax_predicted_mod1","*outprefix,".rst",sep="""))
374

    
375
#### END OF SCRIPT
(7-7/32)