Project

General

Profile

« Previous | Next » 

Revision 8b9df30f

Added by Benoit Parmentier about 8 years ago

initial commit for functions script part 2 global product assessment

View differences:

climate/research/oregon/interpolation/global_product_assessment_part2_functions.R
1
####################################  INTERPOLATION OF TEMPERATURES  #######################################
2
#######################  Assessment of product part 2 functions: mosaic and accuracy ##############################
3
#This script uses the worklfow code applied to the globe. Results currently reside on NEX/PLEIADES NASA.
4
#This part 2 of the assessment focuses on graphics to explore the spatial patterns of raster times series as figures and movie.
5
#AUTHOR: Benoit Parmentier 
6
#CREATED ON: 05/24/2016  
7
#MODIFIED ON: 10/03/2016            
8
#Version: 1
9
#PROJECT: Environmental Layers project     
10
#COMMENTS: Initial commit, script based on part NASA biodiversity conference 
11
#TODO:
12
#1) Add plot broken down by year and region 
13
#2) Modify code for overall assessment accross all regions and year
14
#3) Clean up
15

  
16
#First source these files:
17
#Resolved call issues from R.
18
#source /nobackupp6/aguzman4/climateLayers/sharedModules2/etc/environ.sh 
19
#
20
#setfacl -Rmd user:aguzman4:rwx /nobackupp8/bparmen1/output_run10_1500x4500_global_analyses_pred_1992_10052015
21

  
22
##COMMIT: time profiles run on multiple selected stations and fixing bugs 
23

  
24
#################################################################################################
25

  
26
### Loading R library and packages        
27
#library used in the workflow production:
28
library(gtools)                              # loading some useful tools 
29
library(mgcv)                                # GAM package by Simon Wood
30
library(sp)                                  # Spatial pacakge with class definition by Bivand et al.
31
library(spdep)                               # Spatial pacakge with methods and spatial stat. by Bivand et al.
32
library(rgdal)                               # GDAL wrapper for R, spatial utilities
33
library(gstat)                               # Kriging and co-kriging by Pebesma et al.
34
library(fields)                              # NCAR Spatial Interpolation methods such as kriging, splines
35
library(raster)                              # Hijmans et al. package for raster processing
36
library(gdata)                               # various tools with xls reading, cbindX
37
library(rasterVis)                           # Raster plotting functions
38
library(parallel)                            # Parallelization of processes with multiple cores
39
library(maptools)                            # Tools and functions for sp and other spatial objects e.g. spCbind
40
library(maps)                                # Tools and data for spatial/geographic objects
41
library(reshape)                             # Change shape of object, summarize results
42
library(plotrix)                             # Additional plotting functions
43
library(plyr)                                # Various tools including rbind.fill
44
library(spgwr)                               # GWR method
45
library(automap)                             # Kriging automatic fitting of variogram using gstat
46
library(rgeos)                               # Geometric, topologic library of functions
47
#RPostgreSQL                                 # Interface R and Postgres, not used in this script
48
library(gridExtra)
49
#Additional libraries not used in workflow
50
library(pgirmess)                            # Krusall Wallis test with mulitple options, Kruskalmc {pgirmess}
51
library(colorRamps)
52
library(zoo)
53
library(xts)
54
library(lubridate)
55
library(mosaic)
56

  
57
###### Function used in the script #######
58
  
59
#Used to load RData object saved within the functions produced.
60
load_obj <- function(f){
61
  env <- new.env()
62
  nm <- load(f, env)[1]
63
  env[[nm]]
64
}
65

  
66
pre_process_raster_mosaic_fun <- function(i,list_param){
67
  
68
  
69
  ## Extract parameters
70
  
71
  lf <- list_param$lf
72
  python_bin <- list_param$python_bin
73
  infile_mask <- list_param$infile_mask
74
  scaling <- list_param$scaling
75
  mask_pred <- list_param$mask_pred
76
  matching <- list_param$matching
77
  NA_flag_val <- list_param$NA_flag_val
78
  out_suffix <- list_param$out_suffix
79
  out_dir <- list_param$out_dir
80
  
81
  raster_name_in <- lf[i]
82
  
83
  #Step 1: match extent and resolution
84
  if(matching==TRUE){
85
    lf_files <- c(raster_name_in) #match to mask
86
    rast_ref <- infile_mask
87
    ##Maching resolution is probably only necessary for the r mosaic function
88
    #Modify later to take into account option R or python...
89
    list_param_raster_match <- list(lf_files,rast_ref,file_format,python_bin,out_suffix,out_dir)
90
    names(list_param_raster_match) <- c("lf_files","rast_ref","file_format","python_bin","out_suffix","out_dir_str")
91
    r_pred_matched <- raster_match(1,list_param_raster_match)
92
    raster_name_in <- c(r_pred_matched)
93
  }
94

  
95
  #Step 2: mask
96
  if(mask_pred==TRUE){
97
    r_mask <- raster(infile_mask)
98
    extension_str <- extension(raster_name_in)
99
    raster_name_tmp <- gsub(extension_str,"",basename(raster_name_in))
100
    raster_name <- file.path(out_dir,paste(raster_name_tmp,"_masked.tif",sep = ""))
101
    r_pred <- mask(raster(raster_name_in),r_mask,filename = raster_name,overwrite = TRUE)
102
  }
103
  
104
  NAvalue(r_pred) <- NA_flag_val
105
  #r_pred <- setMinMax(r_pred)
106

  
107
  #Step 3: remove scaling factor
108
  raster_name_in <- filename(r_pred)
109
  extension_str <- extension(raster_name_in)
110
  raster_name_tmp <- gsub(extension_str,"",basename(filename(r_pred)))
111
  raster_name_out <- file.path(out_dir,paste(raster_name_tmp,"_rescaled.tif",sep = ""))
112
  #r_pred <- overlay(r_pred, fun=function(x){x*1/scaling},filename=raster_name,overwrite=T)
113

  
114
  #raster_name_in <- "comp_r_m_use_edge_weights_weighted_mean_gam_CAI_dailyTmax_19990102_reg4_1999_m_gam_CAI_dailyTmax_19990102_reg4_1999_m__meeting_NASA_reg4_04292016_masked.tif"
115
  python_cmd <- file.path(python_bin,"gdal_calc.py")
116
  cmd_str3 <- paste(python_cmd, 
117
                     paste("-A ", raster_name_in,sep=""),
118
                     paste("--outfile=",raster_name_out,sep=""),
119
                     #paste("--type=","Int32",sep=""),
120
                     "--co='COMPRESS=LZW'",
121
                     paste("--NoDataValue=",NA_flag_val,sep=""),
122
                     paste("--calc='(A)*",scaling,"'",sep=""),
123
                     "--overwrite",sep=" ") #division by zero is problematic...
124
  #system(cmd_str3)
125
  system(cmd_str3)
126
  #NAvalue(r_pred) <- NA_flag_val
127
  #r_pred <- 
128
  r_pred <- setMinMax(raster(raster_name_out))
129
  
130
  return(raster_name_out)
131
}
132

  
133
plot_raster_mosaic <- function(i,list_param){
134
  #Function to plot mosaic for poster
135
  #
136
  l_dates <- list_param$l_dates
137
  r_mosaiced_scaled <- list_param$r_mosaiced_scaled
138
  NA_flag_val <- list_param$NA_flag_val
139
  out_dir <- list_param$out_dir
140
  out_suffix <- list_param$out_suffix
141
  region_name <- list_param$region_name
142
  variable_name <- list_param$variable_name
143
  zlim_val <- list_param$zlim_val
144

  
145
  #for (i in 1:length(nlayers(r_mosaic_scaled))){
146
  
147
  date_proc <- l_dates[i]
148
  r_pred <- subset(r_mosaiced_scaled,i)
149
  NAvalue(r_pred)<- NA_flag_val 
150
 
151
  raster_name <- filename(r_pred)
152
  extension_str <- extension(raster_name)
153
  raster_name_tmp <- gsub(extension_str,"",basename(raster_name))
154
  
155
  date_proc <- l_dates[i]
156
  date_val <- as.Date(strptime(date_proc,"%Y%m%d"))
157
  #month_name <- month.name(date_val)
158
  month_str <- format(date_val, "%b") ## Month, char, abbreviated
159
  year_str <- format(date_val, "%Y") ## Year with century
160
  day_str <- as.numeric(format(date_val, "%d")) ## numeric month
161
  date_str <- paste(month_str," ",day_str,", ",year_str,sep="")
162
  
163
  res_pix <- 1200
164
  #res_pix <- 480
165
  col_mfrow <- 1
166
  row_mfrow <- 1
167
  
168
  
169
  if(is.null(zlim_val)){
170
    zlim_val_str <- paste(c(minValue(r_pred),maxValue(r_pred)),sep="_",collapse="_")
171
    #png_filename <-  file.path(out_dir,paste("Figure4_clim_mosaics_day_","_",date_proc,"_",region_name,"_zlim_",zlim_val_str,"_",out_suffix,".png",sep =""))
172
    raster_name_tmp
173
    png_filename <-  file.path(out_dir,paste("Figure_",raster_name_tmp,"_zlim_",zlim_val_str,"_",out_suffix,".png",sep =""))
174
    
175
    title_str <-  paste("Predicted ",variable_name, " on ",date_str , " ", sep = "")
176
  
177
    png(filename=png_filename,width = col_mfrow * res_pix,height = row_mfrow * res_pix)
178

  
179
    plot(r_pred,main =title_str,cex.main =1.5,col=matlab.like(255),
180
       legend.shrink=0.8,legend.width=0.8)
181
       #axis.args = list(cex.axis = 1.6), #control size of legend z
182
       #legend.args=list(text='dNBR', side=4, line=2.5, cex=2.2))
183
       #legend.args=list(text='dNBR', side=4, line=2.49, cex=1.6))
184
    dev.off()
185
  }else{
186
    zlim_val_str <- paste(zlim_val,sep="_",collapse="_")
187
    #png_filename <-  file.path(out_dir,paste("Figure_mosaics_day_","_",date_proc,"_",region_name,"_",zlim_val_str,"_",out_suffix,".png",sep =""))
188
    png_filename <-  file.path(out_dir,paste("Figure_",raster_name_tmp,"_zlim_",zlim_val_str,"_",out_suffix,".png",sep =""))
189

  
190
    title_str <-  paste("Predicted ",variable_name, " on ",date_str , " ", sep = "")
191
    png(filename=png_filename,width = col_mfrow * res_pix,height = row_mfrow * res_pix)
192
    
193
    plot(r_pred,main =title_str,cex.main =1.5,col=matlab.like(255),zlim=zlim_val,
194
       legend.shrink=0.8,legend.width=0.8)
195
       #axis.args = list(cex.axis = 1.6), #control size of legend z
196
       #legend.args=list(text='dNBR', side=4, line=2.5, cex=2.2))
197
       #legend.args=list(text='dNBR', side=4, line=2.49, cex=1.6))
198
    dev.off()
199
  }
200
  return(png_filename)
201
}
202

  
203
extract_date <- function(i,x,item_no=NULL){
204
  y <- unlist(strsplit(x[[i]],"_"))
205
  if(is.null(item_no)){
206
    date_str <- y[length(y)-2] #count from end
207
  }else{
208
    date_str <- y[item_no]
209
  }
210
  return(date_str)
211
}
212

  
213
finding_missing_dates <- function(date_start,date_end,list_dates){
214
  #this assumes daily time steps!!
215
  #can be improved later on
216
  
217
  #date_start <- "19840101"
218
  #date_end <- "19991231"
219
  date1 <- as.Date(strptime(date_start,"%Y%m%d"))
220
  date2 <- as.Date(strptime(date_end,"%Y%m%d"))
221
  dates_range <- seq.Date(date1, date2, by="1 day") #sequence of dates
222

  
223
  missing_dates <- setdiff(as.character(dates_range),as.character(list_dates))
224
  #df_dates_missing <- data.frame(date=missing_dates)
225
  #which(df_dates$date%in%missing_dates)
226
  #df_dates_missing$missing <- 1
227
  
228
  df_dates <- data.frame(date=as.character(dates_range),missing = 0) 
229

  
230
  df_dates$missing[df_dates$date %in% missing_dates] <- 1
231
  #a$flag[a$id %in% temp] <- 1
232

  
233
  missing_dates_obj <- list(missing_dates,df_dates)
234
  names(missing_dates_obj) <- c("missing_dates","df_dates")
235
  return(missing_dates)
236
}
237

  
238

  
239
############################ END OF SCRIPT ##################################

Also available in: Unified diff