Project

General

Profile

« Previous | Next » 

Revision 8a03e5e0

Added by Benoit Parmentier over 8 years ago

functions script used for NASA conference figures production

View differences:

climate/research/oregon/interpolation/NASA2016_conference_temperature_predictions_function.R
1
####################################  INTERPOLATION OF TEMPERATURES  #######################################
2
#######################  NASA 2016 Meeting: biodiversity and ecological forecasting ##############################
3
#This script uses the worklfow code applied to the globe. Results currently reside on NEX/PLEIADES NASA.
4
#Combining tables and figures for individual runs for years and tiles.
5
#Figures and data for the AAG conference are also produced.
6
#AUTHOR: Benoit Parmentier 
7
#CREATED ON: 05/01/2016  
8
#MODIFIED ON: 05/03/2016            
9
#Version: 1
10
#PROJECT: Environmental Layers project     
11
#COMMENTS: Initial commit, script based on part 2 of assessment, will be modified further for overall assessment 
12
#TODO:
13
#1) Add plot broken down by year and region 
14
#2) Modify code for overall assessment accross all regions and year
15
#3) Clean up
16

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

  
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

  
56
###### Function used in the script #######
57
  
58
pre_process_raster_mosaic_fun <- function(i,list_param){
59
  
60
  
61
  ## Extract parameters
62
  
63
  lf <- list_param$lf
64
  python_bin <- list_param$python_bin
65
  infile_mask <- list_param$infile_mask
66
  scaling <- list_param$scaling
67
  mask_pred <- list_param$mask_pred
68
  NA_flag_val <- list_param$NA_flag_val
69
  out_suffix <- list_param$out_suffix
70
  out_dir <- list_param$out_dir
71
  
72
  raster_name_in <- lf[i]
73
  
74
  #Step 1: match extent and resolution
75
  
76
  lf_files <- c(raster_name_in) #match to mask
77
  rast_ref <- infile_mask
78
  ##Maching resolution is probably only necessary for the r mosaic function
79
  #Modify later to take into account option R or python...
80
  list_param_raster_match <- list(lf_files,rast_ref,file_format,python_bin,out_suffix,out_dir)
81
  names(list_param_raster_match) <- c("lf_files","rast_ref","file_format","python_bin","out_suffix","out_dir_str")
82
  r_pred_matched <- raster_match(1,list_param_raster_match)
83
  raster_name_in <- c(r_pred_matched)
84

  
85
  #Step 2: mask
86
  if(mask_pred==TRUE){
87
    r_mask <- raster(infile_mask)
88
    extension_str <- extension(raster_name_in)
89
    raster_name_tmp <- gsub(extension_str,"",basename(raster_name_in))
90
    raster_name <- file.path(out_dir,paste(raster_name_tmp,"_masked.tif",sep = ""))
91
    r_pred <- mask(raster(raster_name_in),r_mask,filename = raster_name,overwrite = TRUE)
92
  }
93
  
94
  NAvalue(r_pred) <- NA_flag_val
95
  #r_pred <- setMinMax(r_pred)
96

  
97
  #Step 3: remove scaling factor
98
  raster_name_in <- filename(r_pred)
99
  extension_str <- extension(raster_name_in)
100
  raster_name_tmp <- gsub(extension_str,"",basename(filename(r_pred)))
101
  raster_name_out <- file.path(out_dir,paste(raster_name_tmp,"_rescaled.tif",sep = ""))
102
  #r_pred <- overlay(r_pred, fun=function(x){x*1/scaling},filename=raster_name,overwrite=T)
103

  
104
  #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"
105
  python_cmd <- file.path(python_bin,"gdal_calc.py")
106
  cmd_str3 <- paste(python_cmd, 
107
                     paste("-A ", raster_name_in,sep=""),
108
                     paste("--outfile=",raster_name_out,sep=""),
109
                     #paste("--type=","Int32",sep=""),
110
                     "--co='COMPRESS=LZW'",
111
                     paste("--NoDataValue=",NA_flag_val,sep=""),
112
                     paste("--calc='(A)*",scaling,"'",sep=""),
113
                     "--overwrite",sep=" ") #division by zero is problematic...
114
  #system(cmd_str3)
115
  system(cmd_str3)
116
  #NAvalue(r_pred) <- NA_flag_val
117
  #r_pred <- 
118
  r_pred <- setMinMax(raster(raster_name_out))
119
  
120
  return(raster_name_out)
121
}
122

  
123
plot_raster_mosaic <- function(i,list_param){
124
  #Function to plot mosaic for poster
125
  #
126
  l_dates <- list_param$l_dates
127
  r_mosaiced_scaled <- list_param$r_mosaiced_scaled
128
  NA_flag_val <- list_param$NA_flag_val
129
  out_dir <- list_param$out_dir
130
  out_suffix <- list_param$out_suffix
131
  region_name <- list_param$region_name
132
  variable_name <- list_param$variable_name
133

  
134
#for (i in 1:length(nlayers(r_mosaic_scaled))){
135
  
136
  date_proc <- l_dates[i]
137
  r_pred <- subset(r_mosaic_scaled,i)
138
  NAvalue(r_pred)<- NA_flag_val 
139
 
140
  date_proc <- l_dates[i]
141
  date_val <- as.Date(strptime(date_proc,"%Y%m%d"))
142
  #month_name <- month.name(date_val)
143
  month_str <- format(date_val, "%b") ## Month, char, abbreviated
144
  year_str <- format(date_val, "%Y") ## Year with century
145
  day_str <- as.numeric(format(date_val, "%d")) ## numeric month
146
  date_str <- paste(month_str," ",day_str,", ",year_str,sep="")
147
  
148
  res_pix <- 1200
149
  #res_pix <- 480
150
  col_mfrow <- 1
151
  row_mfrow <- 1
152
  
153
  png_filename <-  file.path(out_dir,paste("Figure4_clim_mosaics_day_","_",date_proc,"_",region_name,"_",out_suffix,".png",sep =""))
154
  title_str <-  paste("Predicted ",variable_name, " on ",date_str , " ", sep = "")
155
  
156
  png(filename=png_filename,width = col_mfrow * res_pix,height = row_mfrow * res_pix)
157
  plot(r_pred,main =title_str,cex.main =1.5,col=matlab.like(255),zlim=c(-50,50),
158
       legend.shrink=0.8,legend.width=0.8)
159
       #axis.args = list(cex.axis = 1.6), #control size of legend z
160
       #legend.args=list(text='dNBR', side=4, line=2.5, cex=2.2))
161
       #legend.args=list(text='dNBR', side=4, line=2.49, cex=1.6))
162
  dev.off()
163

  
164
  return(png_filename)
165
}
166

  
167
extract_date <- function(i,x,item_no=NULL){
168
  y <- unlist(strsplit(x[[i]],"_"))
169
  if(is.null(item_no)){
170
    date_str <- y[length(y)-2] #count from end
171
  }else{
172
    date_str <- y[item_no]
173
  }
174
  return(date_str)
175
}
176

  
177
############################ END OF SCRIPT ##################################

Also available in: Unified diff