Project

General

Profile

« Previous | Next » 

Revision e7fa7bc9

Added by Benoit Parmentier almost 12 years ago

FUSION, GAM and fusion comparison raster prediction modified return object to solve memory issues in mod object

View differences:

climate/research/oregon/interpolation/fusion_gam_prediction_reg.R
17 17
library(gstat)                               # Kriging and co-kriging by Pebesma et al.
18 18
library(fields)                              # NCAR Spatial Interpolation methods such as kriging, splines
19 19
library(raster)                              # Hijmans et al. package for raster processing
20
library(rasterVis)
20 21
library(parallel)                            # Urbanek S. and Ripley B., package for multi cores & parralel processing
21 22

  
22 23
### Parameters and argument
23 24

  
24 25
infile1<- "ghcn_or_tmax_covariates_06262012_OR83M.shp"             #GHCN shapefile containing variables for modeling 2010                 
25
#infile2<-"list_10_dates_04212012.txt"                     #List of 10 dates for the regression
26
#tinfile2<-"list_10_dates_04212012.txt"                     #List of 10 dates for the regression
26 27
#infile2<-"list_2_dates_04212012.txt"
27 28
infile2<-"list_365_dates_04212012.txt"
28 29
infile3<-"LST_dates_var_names.txt"                        #LST dates name
......
30 31
infile5<-"mean_day244_rescaled.rst"                       #Raster or grid for the locations of predictions
31 32
#infile6<-"lst_climatology.txt"
32 33
infile6<-"LST_files_monthly_climatology.txt"
34
inlistf<-"list_files_05032012.txt"                        #Stack of images containing the Covariates
35

  
36

  
33 37
#path<-"/home/parmentier/Data/IPLANT_project/data_Oregon_stations"
34
path<-"/home/parmentier/Data/IPLANT_project/data_Oregon_stations"
38
path<-"/home/parmentier/Data/IPLANT_project/data_Oregon_stations_07192012_GAM"
39
#path<-"/home/parmentier/Data/IPLANT_project/data_Oregon_stations_GAM"
35 40
#path<-"/home/parmentier/Data/IPLANT_project/data_Oregon_stations_07152012"     #Jupiter LOCATION on Atlas for kriging"
36 41
#path<-"M:/Data/IPLANT_project/data_Oregon_stations"   #Locations on Atlas
37 42

  
......
40 45
#GHCN Database for 1980-2010 for study area (OR) 
41 46
data3<-read.table(paste(path,"/","ghcn_data_TMAXy1980_2010_OR_0602012.txt",sep=""),sep=",", header=TRUE)
42 47

  
48
nmodels<-8   #number of models running
49
y_var_name<-"dailyTmax"
50
predval<-1
43 51
prop<-0.3                                                                           #Proportion of testing retained for validation   
44 52
#prop<-0.25
45 53
seed_number<- 100                                                                   #Seed number for random sampling
46
out_prefix<-"_07152012_10d_fusion17"                                                   #User defined output prefix
54
out_prefix<-"_07242012_365d_GAM_fusion5"                                                   #User defined output prefix
47 55
setwd(path)
48 56
bias_val<-0            #if value 1 then training data is used in the bias surface rather than the all monthly stations
49 57

  
50 58
#source("fusion_function_07192012.R")
51
source("fusion_function_07192012.R")
59
source("GAM_fusion_function_07192012d.R")
52 60
############ START OF THE SCRIPT ##################
53 61
#
54 62
#
55 63
### Step 0/Step 6 in Brian's code...preparing year 2010 data for modeling 
56 64
#
57 65

  
58

  
59 66
###Reading the station data and setting up for models' comparison
60 67
filename<-sub(".shp","",infile1)             #Removing the extension from file.
61 68
ghcn<-readOGR(".", filename)                 #reading shapefile 
......
65 72
mean_LST<- readGDAL(infile5)                 #Reading the whole raster in memory. This provides a grid for kriging
66 73
proj4string(mean_LST)<-CRS                   #Assigning coordinate information to prediction grid.
67 74

  
68
ghcn = transform(ghcn,Northness = cos(ASPECT*pi/180)) #Adding a variable to the dataframe
69
ghcn = transform(ghcn,Eastness = sin(ASPECT*pi/180))  #adding variable to the dataframe.
70
ghcn = transform(ghcn,Northness_w = sin(slope*pi/180)*cos(ASPECT*pi/180)) #Adding a variable to the dataframe
71
ghcn = transform(ghcn,Eastness_w = sin(slope*pi/180)*sin(ASPECT*pi/180))  #adding variable to the dataframe.
75
ghcn <- transform(ghcn,Northness = cos(ASPECT*pi/180)) #Adding a variable to the dataframe
76
ghcn <- transform(ghcn,Eastness = sin(ASPECT*pi/180))  #adding variable to the dataframe.
77
ghcn <- transform(ghcn,Northness_w = sin(slope*pi/180)*cos(ASPECT*pi/180)) #Adding a variable to the dataframe
78
ghcn <- transform(ghcn,Eastness_w = sin(slope*pi/180)*sin(ASPECT*pi/180))  #adding variable to the dataframe.
72 79

  
73 80
#Remove NA for LC and CANHEIGHT
74 81
ghcn$LC1[is.na(ghcn$LC1)]<-0
......
79 86
LST_dates <-readLines(paste(path,"/",infile3, sep=""))
80 87
models <-readLines(paste(path,"/",infile4, sep=""))
81 88

  
82
# #Model assessment: specific diagnostic/metrics for GAM
83
# results_AIC<- matrix(1,length(dates),length(models)+3)  
84
# results_GCV<- matrix(1,length(dates),length(models)+3)
85
# results_DEV<- matrix(1,length(dates),length(models)+3)
86
# results_RMSE_f<- matrix(1,length(dates),length(models)+3)
87
# 
88
# #Model assessment: general diagnostic/metrics 
89
# results_RMSE <- matrix(1,length(dates),length(models)+4)
90
# results_MAE <- matrix(1,length(dates),length(models)+4)
91
# results_ME <- matrix(1,length(dates),length(models)+4)       #There are 8+1 models
92
# results_R2 <- matrix(1,length(dates),length(models)+4)       #Coef. of determination for the validation dataset
93
# 
94
# results_RMSE_f<- matrix(1,length(dates),length(models)+4)    #RMSE fit, RMSE for the training dataset
95

  
96
#Model assessment: specific diagnostic/metrics for GAM
97
results_AIC<- matrix(1,1,length(models)+3)  
98
results_GCV<- matrix(1,1,length(models)+3)
99
results_DEV<- matrix(1,1,length(models)+3)
89
##Extracting the variables values from the raster files                                             
90

  
91
lines<-read.table(paste(path,"/",inlistf,sep=""), sep=" ")                  #Column 1 contains the names of raster files
92
inlistvar<-lines[,1]
93
inlistvar<-paste(path,"/",as.character(inlistvar),sep="")
94
covar_names<-as.character(lines[,2])                                         #Column two contains short names for covaraites
95

  
96
s_raster<- stack(inlistvar)                                                  #Creating a stack of raster images from the list of variables.
97
layerNames(s_raster)<-covar_names                                            #Assigning names to the raster layers
98
projection(s_raster)<-CRS
99

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

  
110
pos<-match("LC1",layerNames(s_raster)) #Find column with name "value"
111
LC1<-raster(s_raster,layer=pos)             #Select layer from stack
112
s_raster<-dropLayer(s_raster,pos)
113
LC1[is.na(LC1)]<-0
114
pos<-match("LC3",layerNames(s_raster)) #Find column with name "value"
115
LC3<-raster(s_raster,layer=pos)             #Select layer from stack
116
s_raster<-dropLayer(s_raster,pos)
117
LC3[is.na(LC3)]<-0
118

  
119
xy<-coordinates(r1)  #get x and y projected coordinates...
120
xy_latlon<-project(xy, CRS, inv=TRUE) # find lat long for projected coordinats (or pixels...)
121
lon<-raster(xy_latlon) #Transform a matrix into a raster object ncol=ncol(r1), nrow=nrow(r1))
122
ncol(lon)<-ncol(r1)
123
nrow(lon)<-nrow(r1)
124
extent(lon)<-extent(r1)
125
projection(lon)<-CRS  #At this stage this is still an empty raster with 536 nrow and 745 ncell 
126
lat<-lon
127
values(lon)<-xy_latlon[,1]
128
values(lat)<-xy_latlon[,2]
129

  
130
r<-stack(N,E,Nw,Ew,lon,lat,LC1,LC3)
131
rnames<-c("Northness","Eastness","Northness_w","Eastness_w", "lon","lat","LC1","LC3")
132
layerNames(r)<-rnames
133
s_raster<-addLayer(s_raster, r)
134

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

  
137
####### Preparing LST stack of climatology...
138

  
139
#l=list.files(pattern="mean_month.*rescaled.rst")
140
l <-readLines(paste(path,"/",infile6, sep=""))
141
molst<-stack(l)  #Creating a raster stack...
142
#setwd(old)
143
molst<-molst-273.16  #K->C          #LST stack of monthly average...
144
idx <- seq(as.Date('2010-01-15'), as.Date('2010-12-15'), 'month')
145
molst <- setZ(molst, idx)
146
layerNames(molst) <- month.abb
147

  
148

  
149
######  Preparing tables for model assessment: specific diagnostic/metrics
150

  
151
#Model assessment: specific diagnostics/metrics
152
results_AIC<- matrix(1,1,nmodels+3)  
153
results_GCV<- matrix(1,1,nmodels+3)
154
results_DEV<- matrix(1,1,nmodels+3)
100 155
#results_RMSE_f<- matrix(1,length(models)+3)
101 156

  
102 157
#Model assessment: general diagnostic/metrics 
103
results_RMSE <- matrix(1,1,length(models)+4)
104
results_MAE <- matrix(1,1,length(models)+4)
105
results_ME <- matrix(1,1,length(models)+4)       #There are 8+1 models
106
results_R2 <- matrix(1,1,length(models)+4)       #Coef. of determination for the validation dataset
158
results_RMSE <- matrix(1,1,nmodels+4)
159
results_MAE <- matrix(1,1,nmodels+4)
160
results_ME <- matrix(1,1,nmodels+4)       #There are 8+1 models
161
results_R2 <- matrix(1,1,nmodels+4)       #Coef. of determination for the validation dataset
162

  
163
results_RMSE_f<- matrix(1,1,nmodels+4)    #RMSE fit, RMSE for the training dataset
164
results_MAE_f <- matrix(1,1,nmodels+4)
165

  
166
######## Preparing monthly averages from the ProstGres database
167

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

  
108
results_RMSE_f<- matrix(1,1,length(models)+4)    #RMSE fit, RMSE for the training dataset
109
results_MAE_f <- matrix(1,1,length(models)+4)
178
dst<-merge(d1, stat_loc, by.x="station", by.y="STAT_ID")   #Inner join all columns are retained
179

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

  
186
######### Preparing daily values for training and testing
110 187

  
111 188
#Screening for bad values: value is tmax in this case
112 189
#ghcn$value<-as.numeric(ghcn$value)
......
116 193
ghcn<-ghcn_test2
117 194
#coords<- ghcn[,c('x_OR83M','y_OR83M')]
118 195

  
196
##Sampling: training and testing sites...
197

  
119 198
set.seed(seed_number)                        #Using a seed number allow results based on random number to be compared...
120 199
ghcn.subsets <-lapply(dates, function(d) subset(ghcn, date==d)) #this creates a list of 10 or 365 subsets dataset based on dates
121 200
sampling<-vector("list",length(dates))
......
129 208
sampling[[i]]<-ind.training
130 209
}
131 210

  
211
######## Prediction for the range of dates
212

  
132 213
#Start loop here...
133 214

  
134 215
## looping through the dates...this is the main part of the code
......
137 218
#for(i in 1:length(dates)){     [[       # start of the for loop #1
138 219
#i=1
139 220

  
140

  
141 221
#mclapply(1:length(dates), runFusion, mc.cores = 8)#This is the end bracket from mclapply(...) statement
222
#source("GAM_fusion_function_07192012d.R")
142 223

  
143
fusion_mod<-mclapply(1:length(dates), runFusion, mc.cores = 8)#This is the end bracket from mclapply(...) statement
224
gam_fus_mod<-mclapply(1:length(dates), runGAMFusion,mc.preschedule=FALSE,mc.cores = 8) #This is the end bracket from mclapply(...) statement
144 225
#fusion_mod357<-mclapply(357:365,runFusion, mc.cores=8)# for debugging
145 226
#test<-runFusion(362) #date 362 has problems with GAM
146 227
#test<-mclapply(357,runFusion, mc.cores=1)# for debugging
......
152 233
}
153 234

  
154 235

  
155
tb<-fusion_mod[[1]][[3]][0,]  #empty data frame with metric table structure that can be used in rbinding...
156
tb_tmp<-fusion_mod #copy
236
tb<-gam_fus_mod[[1]][[3]][0,]  #empty data frame with metric table structure that can be used in rbinding...
237
tb_tmp<-gam_fus_mod #copy
157 238

  
158 239
for (i in 1:length(tb_tmp)){
159 240
  tmp<-tb_tmp[[i]][[3]]
......
183 264

  
184 265
write.table(tb_diagnostic1, file= paste(path,"/","results2_fusion_Assessment_measure1",out_prefix,".txt",sep=""), sep=",")
185 266
write.table(tb, file= paste(path,"/","results2_fusion_Assessment_measure_all",out_prefix,".txt",sep=""), sep=",")
186

  
267
save(gam_fus_mod,file= paste(path,"/","results2_fusion_Assessment_measure_all",out_prefix,".RData",sep=""))
187 268
#tb<-as.data.frame(tb_diagnostic1)
188 269

  
189 270
#write.table(tb_1, file= paste(path,"/","results2_fusion_Assessment_measure1",out_prefix,".txt",sep=""), sep=",")

Also available in: Unified diff