Project

General

Profile

« Previous | Next » 

Revision 43e4187c

Added by Benoit Parmentier about 9 years ago

global assessment part2 script moved m functions to script

View differences:

climate/research/oregon/interpolation/global_run_scalingup_assessment_part2.R
5 5
#Analyses, figures, tables and data are also produced in the script.
6 6
#AUTHOR: Benoit Parmentier 
7 7
#CREATED ON: 03/23/2014  
8
#MODIFIED ON: 09/22/2015            
8
#MODIFIED ON: 09/23/2015            
9 9
#Version: 4
10 10
#PROJECT: Environmental Layers project     
11 11
#COMMENTS: analyses for run 10 global analyses,all regions 1500x4500km with additional tiles to increase overlap 
......
49 49

  
50 50
function_analyses_paper1 <-"contribution_of_covariates_paper_interpolation_functions_07182014.R" #first interp paper
51 51
function_analyses_paper2 <-"multi_timescales_paper_interpolation_functions_08132014.R"
52
function_global_run_assessment_part2 <- "global_run_scalingup_assessment_part2_functions_0923015.R"
52 53

  
53 54
load_obj <- function(f)
54 55
{
......
69 70
  return(out_dir)
70 71
}
71 72

  
72
 #Remove models that were not fitted from the list
73
#All modesl that are "try-error" are removed
74
remove_errors_list<-function(list_items){
75
  
76
  #This function removes "error" items in a list
77
  list_tmp<-list_items
78
    if(is.null(names(list_tmp))){
79
    names(list_tmp) <- paste("l",1:length(list_tmp),sep="_")
80
    names(list_items) <- paste("l",1:length(list_tmp),sep="_")
81
  }
82

  
83
  for(i in 1:length(list_items)){
84
    if(inherits(list_items[[i]],"try-error")){
85
      list_tmp[[i]]<-0
86
    }else{
87
    list_tmp[[i]]<-1
88
   }
89
  }
90
  cnames<-names(list_tmp[list_tmp>0])
91
  x <- list_items[match(cnames,names(list_items))]
92
  return(x)
93
}
94

  
95
#turn term from list into data.frame
96
#name_col<-function(i,x){
97
#x_mat<-x[[i]]
98
#x_df<-as.data.frame(x_mat)
99
#x_df$mod_name<-rep(names(x)[i],nrow(x_df))
100
#x_df$term_name <-row.names(x_df)
101
#return(x_df)
102
#}
103
#Function to rasterize a table with coordinates and variables...,maybe add option for ref image??
104
rasterize_df_fun <- function(data_tb,coord_names,proj_str,out_suffix,out_dir=".",file_format=".rst",NA_flag_val=-9999,tolerance_val= 0.000120005){
105
  data_spdf <- data_tb
106
  coordinates(data_spdf) <- cbind(data_spdf[[coord_names[1]]],data_spdf[[coord_names[2]]])
107
  proj4string(data_spdf) <- proj_str
108

  
109
  data_pix <- try(as(data_spdf,"SpatialPixelsDataFrame"))
110
  #tolerance_val <- 0.000120005 
111
  #tolerance_val <- 0.000856898
112
  if(inherits(data_pix,"try-error")){
113
      data_pix <- SpatialPixelsDataFrame(data_spdf, data=data_spdf@data, tolerance=tolerance_val) 
114
  }
115
  
116
  #test <- as(data_spdf,"SpatialPixelsDataFrame")
117

  
118
  # set up an 'empty' raster, here via an extent object derived from your data
119
  #e <- extent(s100[,1:2])
120
  #e <- e + 1000 # add this as all y's are the same
121

  
122
  #r <- raster(e, ncol=10, nrow=2)
123
  # or r <- raster(xmn=, xmx=,  ...
124

  
125
  data_grid <- as(data_pix,"SpatialGridDataFrame") #making it a regural grid
126
  r_ref <- raster(data_grid) #this is the ref image
127
  rast_list <- vector("list",length=ncol(data_tb))
128
  
129
  for(i in 1:(ncol(data_tb))){
130
    field_name <- names(data_tb)[i]
131
    var <- as.numeric(data_spdf[[field_name]])
132
    data_spdf$var  <- var
133
    #r <-rasterize(data_spdf,r_ref,field_name)
134
    r <-rasterize(data_spdf,r_ref,"var",NAflag=NA_flag_val,fun=mean) #prolem with NA in NDVI!!
135

  
136
    data_name<-paste("r_",field_name,sep="") #can add more later...
137
    #raster_name<-paste(data_name,out_names[j],".tif", sep="")
138
    raster_name<-paste(data_name,out_suffix,file_format, sep="")
139
  
140
    writeRaster(r, NAflag=NA_flag_val,filename=file.path(out_dir,raster_name),overwrite=TRUE)
141
    #Writing the data in a raster file format...
142
    rast_list[i] <-file.path(out_dir,raster_name)
143
  }
144
  return(unlist(rast_list))
145
}
146

  
147
plot_raster_tb_diagnostic <- function(reg_layer,tb_dat,df_tile_processed,date_selected,mod_selected,var_selected,out_suffix){
148
  
149
  test <- subset(tb_dat,pred_mod==mod_selected & date==date_selected,select=c("tile_id",var_selected))
150

  
151
  test_data_tb <- merge(df_tile_processed,test,by="tile_id",all=T) #keep all
152
  test_r <- subset(test_data_tb,select=c("lat","lon","tile_id",var_selected))
153
  out_suffix_str <- paste(var_selected,mod_selected,date_selected,out_suffix,sep="_")
154
  coord_names <- c("lon","lat")
155
  l_rast <- rasterize_df_fun(test_r,coord_names,proj_str,out_suffix_str,out_dir=".",file_format=".tif",NA_flag_val=-9999,tolerance_val=0.000120005)
156
  #mod_kr_stack <- stack(mod_kr_l_rast)
157
  d_tb_rast <- stack(l_rast)
158
  names(d_tb_rast) <- names(test_r)
159
  #plot(d_tb_rast)
160
  r <- subset(d_tb_rast,"rmse")
161
  names(r) <- paste(mod_selected,var_selected,date_selected,sep="_")
162
  #plot info: with labels
163

  
164
  res_pix <- 1200
165
  col_mfrow <- 1
166
  row_mfrow <- 1
167

  
168
  png(filename=paste("Figure9_",names(r),"_map_processed_region_",region_name,"_",out_suffix,".png",sep=""),
169
    width=col_mfrow*res_pix,height=row_mfrow*res_pix)
170

  
171
  #plot(reg_layer)
172
  #p1 <- spplot(reg_layer,"ISO",colorkey=FALSE) #Use ISO instead of NAME_1 to see no color?
173
  title_str <- paste(names(r),"for ", region_name,sep="")
174

  
175
  p0 <- levelplot(r,col.regions=matlab.like(25),margin=F,main=title_str)
176
  p_shp <- layer(sp.polygons(reg_layer, lwd=1, col='black'))
177

  
178
  p <- p0 + p_shp
179
  print(p)
180

  
181
  dev.off()
182

  
183
}
184

  
185
create_raster_from_tb_diagnostic <- function(i,list_param){
186
  #create a raster image using tile centroids and given fields  from tb diagnostic data
187
  tb_dat <- list_param$tb_dat
188
  df_tile_processed <- list_param$df_tile_processed
189
  date_selected <- list_param$date_selected[i]
190
  mod_selected <- list_param$mod_selected
191
  var_selected <- list_param$var_selected
192
  out_suffix <- list_param$out_suffix
193
  
194
  test <- subset(tb_dat,pred_mod==mod_selected & date==date_selected,select=c("tile_id",var_selected))
195

  
196
  test_data_tb <- merge(df_tile_processed,test,by="tile_id",all=T) #keep all
197
  test_r <- subset(test_data_tb,select=c("lat","lon","tile_id",var_selected))
198
  out_suffix_str <- paste(var_selected,mod_selected,date_selected,out_suffix,sep="_")
199
  coord_names <- c("lon","lat")
200
  l_rast <- rasterize_df_fun(test_r,coord_names,proj_str,out_suffix_str,out_dir=".",file_format,NA_flag_val,tolerance_val=0.000120005)
201
  #mod_kr_stack <- stack(mod_kr_l_rast)
202
  #d_tb_rast <- stack(l_rast)
203
  #r <- subset(d_tb_rast,var_selected)
204
  #names(d_tb_rast) <- names(test_r)
205
  return(l_rast[4])
206
}
207

  
208
assign_FID_spatial_polygons_df <-function(list_spdf,ID_str=NULL){
209
  list_spdf_tmp <- vector("list",length(list_spdf))
210
  if(is.null(ID_str)){
211
    nf <- 0 #number of features
212
    #for(i in 1:length(spdf)){
213
    #    shp1 <- list_spdf[[i]]
214
    #    f <- nrow(shp1)
215
    #    nf <- nf + f
216
    #}
217
    #This assumes that the list has one feature per item list
218
    nf <- length(list_spdf)
219
    ID_str <- as.character(1:nf)
220
  }
221
  for(i in 1:length(list_spdf)){
222
    #test=spRbind(shps_tiles[[1]],shps_tiles[[2]])
223
    shp1 <- list_spdf[[i]]
224
    shp1$FID <- ID_str
225
    shp1<- spChFIDs(shp1, as.character(shp1$FID)) #assign ID
226
    list_spdf_tmp[[i]]  <-shp1
227
  }
228
  return(list_spdf_tmp)
229
}
230

  
231
combine_spatial_polygons_df_fun <- function(list_spdf_tmp,ID_str=NULL){
232
  if(is.null(ID_str)){
233
    #call function
234
    list_spdf_tmp <- assign_FID_spatial_polygons_df
235
  }
236
  combined_spdf <- list_spdf_tmp[[1]]
237
  for(i in 2:length(list_spdf_tmp)){
238
    combined_spdf <- rbind(combined_spdf,list_spdf_tmp[[i]])
239
    #sapply(slot(shps_tiles[[2]], "polygons"), function(x) slot(x, "ID"))
240
    #rownames(as(alaska.tract, "data.frame"))
241
  }
242
  return(combined_spdf)
243
}
244

  
245
plot_daily_mosaics <- function(i,list_param_plot_daily_mosaics){
246
  #Purpose:
247
  #This functions mask mosaics files for a default range (-100,100 deg).
248
  #It produces a masked tif in a given dataType format (FLT4S)
249
  #It creates a figure of mosaiced region being interpolated.
250
  #Author: Benoit Parmentier
251
  #Parameters:
252
  #lf_m: list of files 
253
  #reg_name:region name with tile size included
254
  #To do:
255
  #Add filenames
256
  #Add range
257
  #Add output dir
258
  #Add dataType_val option
259
  
260
  ##### BEGIN ########
261
  
262
  #Parse the list of parameters
263
  lf_m <- list_param_plot_daily_mosaics$lf_m
264
  reg_name <- list_param_plot_daily_mosaics$reg_name
265
  out_dir_str <- list_param_plot_daily_mosaics$out_dir_str
266
  out_suffix <- list_param_plot_daily_mosaics$out_suffix
267
  l_dates <- list_param_plot_daily_mosaics$l_dates
268

  
269

  
270
  #list_param_plot_daily_mosaics <- list(lf_m=lf_m,reg_name=reg_name,out_dir_str=out_dir_str)
271

  
272
  
273
  #rast_list <- vector("list",length=length(lf_m))
274
  r_test<- raster(lf_m[i])
275

  
276
  m <- c(-Inf, -100, NA,  
277
         -100, 100, 1, 
278
         100, Inf, NA) #can change the thresholds later
279
  rclmat <- matrix(m, ncol=3, byrow=TRUE)
280
  rc <- reclassify(r_test, rclmat,filename=paste("rc_tmp_",i,".tif",sep=""),dataType="FLT4S",overwrite=T)
281
  file_name <- unlist(strsplit(basename(lf_m[i]),"_"))
282
  
283
  #date_proc <- file_name[7] #specific tot he current naming of files
284
  date_proc <- l_dates[i]
285
  #paste(raster_name[1:7],collapse="_")
286
  #add filename option later
287
  extension_str <- extension(filename(r_test))
288
  raster_name_tmp <- gsub(extension_str,"",basename(filename(r_test)))
289
  raster_name <- file.path(out_dir_str,paste(raster_name_tmp,"_masked.tif",sep=""))
290
  r_pred <- mask(r_test,rc,filename=raster_name,overwrite=TRUE)
291
  
292
  res_pix <- 1200
293
  #res_pix <- 480
294

  
295
  col_mfrow <- 1
296
  row_mfrow <- 1
297
  
298
  png(filename=paste("Figure9_clim_mosaics_day_test","_",date_proc,"_",reg_name,"_",out_suffix,".png",sep=""),
299
    width=col_mfrow*res_pix,height=row_mfrow*res_pix)
300

  
301
  plot(r_pred,main=paste("Predicted on ",date_proc , " ", reg_name,sep=""),cex.main=1.5)
302
  dev.off()
303
  
304
  return(raster_name)
305
  
306
}
307

  
308
plot_screen_raster_val<-function(i,list_param){
309
  ##USAGE###
310
  #Screen raster list and produced plot as png.
311
  fname <-list_param$lf_raster_fname[i]
312
  screenRast <- list_param$screenRast
313
  l_dates<- list_param$l_dates
314
  out_dir_str <- list_param$out_dir_str
315
  prefix_str <-list_param$prefix_str
316
  out_suffix_str <- list_param$out_suffix_str
317
  
318
  ### START SCRIPT ####
319
  date_proc <- l_dates[i]
320
  
321
  if(screenRast==TRUE){
322
    r_test <- raster(fname)
323

  
324
    m <- c(-Inf, -100, NA,  
325
         -100, 100, 1, 
326
         100, Inf, NA) #can change the thresholds later
327
    rclmat <- matrix(m, ncol=3, byrow=TRUE)
328
    rc <- reclassify(r_test, rclmat,filename=paste("rc_tmp_",i,".tif",sep=""),dataType="FLT4S",overwrite=T)
329
    #file_name <- unlist(strsplit(basename(lf_m[i]),"_"))
330
    extension_str <- extension(filename(r_test))
331
    raster_name_tmp <- gsub(extension_str,"",basename(filename(r_test)))
332
    raster_name <- file.path(out_dir_str,paste(raster_name_tmp,"_masked.tif",sep=""))
333
  
334
    r_pred <- mask(r_test,rc,filename=raster_name,overwrite=TRUE)
335
  }else{
336
    r_pred <- raster(fname)
337
  }
338
  
339
  #date_proc <- file_name[7] #specific tot he current naming of files
340
  #date_proc<- "2010010101"
341

  
342
  #paste(raster_name[1:7],collapse="_")
343
  #add filename option later
344

  
345
  res_pix <- 960
346
  #res_pix <- 480
347

  
348
  col_mfrow <- 1
349
  row_mfrow <- 1
350
  
351
#  png(filename=paste("Figure10_clim_world_mosaics_day_","_",date_proc,"_",tile_size,"_",out_suffix,".png",sep=""),
352
#    width=col_mfrow*res_pix,height=row_mfrow*res_pix)
353
  png(filename=paste(prefix_str,"_",date_proc,"_",tile_size,"_",out_suffix_str,".png",sep=""),
354
    width=col_mfrow*res_pix,height=row_mfrow*res_pix)
355

  
356
  plot(r_pred,main=paste("Predicted on ",date_proc , " ", tile_size,sep=""),cex.main=1.5)
357
  dev.off()
358

  
359
}
360 73

  
361 74
############################################
362 75
#### Parameters and constants  

Also available in: Unified diff