Project

General

Profile

« Previous | Next » 

Revision d0df33ae

Added by Benoit Parmentier over 11 years ago

AAG 2013 figures, covariates stack, screening and modification to allow continuity for Oregon TMAX

View differences:

climate/research/oregon/interpolation/AAG2013_conference_Oregon_interpolation.R
1 1
####################################  INTERPOLATION TEMPERATURES  #######################################
2
############################      SCRIPT 1- MEOT          #######################################
2
############################  AAG 2013 and OREGON transitition script #######################################
3 3
#This script reads information concerning the Oregon case study to adapt data for the revised 
4 4
# interpolation code.
5 5
#Figures and data for the AAG conference are also produced.
6 6
#AUTHOR: Benoit Parmentier                                                                      #
7
#DATE: 04/03/2013            
7
#DATE: 04/05/2013            
8 8
#Version: 1
9 9
#PROJECT: Environmental Layers project                                       #
10 10
#################################################################################################
......
26 26
library(reshape)
27 27
library(plotrix)
28 28

  
29
#### UNCTION USED IN SCRIPT
30

  
31
create_modis_tiles_region<-function(tiles,modis_sp){
32
  #This functions returns a subset of tiles from the modis grdi.
33
  #Arguments: modies grid tile,list of tiles
34
  #Output: spatial grid data frame of the subset of tiles
35
  
36
  h_list<-lapply(tiles,substr,start=2,stop=3) #passing multiple arguments
37
  v_list<-lapply(tiles,substr,start=5,stop=6) #passing multiple arguments
38
  selected_tiles<-subset(subset(modis_sp,subset = h %in% as.numeric (h_list) ),
39
                         subset = v %in% as.numeric(v_list)) 
40
  return(selected_tiles)
41
}
42

  
29 43
### Parameters and argument
30 44

  
31 45
lc_path<-"/home/layers/data/land-cover/lc-consensus-global"
......
37 51

  
38 52
#infile_reg_outline=""  #input region outline defined by polygon
39 53
infile_reg_outline= "OR83M_state_outline.shp"
54
infile_countries_sinusoidal<-"countries_sinusoidal_world.shp"
40 55

  
41 56
#CRS_interp<-"+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs";
42 57
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";
43 58
CRS_locs_WGS84<-CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +towgs84=0,0,0") #Station coords WGS84
44 59
out_region_name<-"Oregon_region" #generated on the fly
45
out_suffix<-"_OR_04032013"
60
out_prefix<-"_OR_04052013"
46 61
ref_rast_name<- "mean_day244_rescaled.rst"                     #This is the shape file of outline of the study area. #local raster name defining resolution, exent, local projection--. set on the fly??
47 62

  
48 63
#The names of covariates can be changed...these names should be output/input from covar script!!!
......
57 72
in_path<- "/home/parmentier/Data/IPLANT_project/Oregon_interpolation/Oregon_covariates"
58 73
setwd(in_path)
59 74

  
60

  
61 75
####################################################
62 76
#Read in GHCND database station locations
63 77

  
......
68 82
coordinates(dat_stat)<-coords
69 83
proj4string(dat_stat)<-CRS_locs_WGS84 #this is the WGS84 projection
70 84
#Save shapefile for later
71

  
85
interp_area <- readOGR(dsn=in_path,sub(".shp","",infile_reg_outline))
86
interp_area_WGS84 <-spTransform(interp_area,CRS_locs_WGS84)         # Project from WGS84 to new coord. system
72 87

  
73 88
# Spatial query to find relevant stations
74 89

  
75
dat_stat2<-spTransform(dat_stat,CRS(CRS_interp))         # Project from WGS84 to new coord. system
76

  
77
#dat_stat2<-spTransform(dat_stat,CRS(CRS_interp))         # Project from WGS84 to new coord. system
78
interp_area <- readOGR(dsn=in_path,sub(".shp","",infile_reg_outline))
79

  
80
inside <- !is.na(over(dat_stat2, as(interp_area, "SpatialPolygons")))  #Finding stations contained in the current interpolation area
81
stat_reg<-dat_stat2[inside,]              #Selecting stations contained in the current interpolation area
90
inside <- !is.na(over(dat_stat, as(interp_area_WGS84, "SpatialPolygons")))  #Finding stations contained in the current interpolation area
91
stat_reg<-dat_stat[inside,]              #Selecting stations contained in the current interpolation area
82 92

  
83 93
#Read in world map 
84

  
85
#Get Natural Earth Data using rworldmap package:
86
#Derived from http://www.naturalearthdata.com/downloads/110m-cultural-vectors/110m-admin-0-countries/
87
#world_sp <- getData("GADM", country="FRA",level=0)  # different resolutions available
88 94
world_sp <- getData("countries")  # different resolutions available
89
#proj4string(world_sp)<-"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
90
#proj4string(world_sp)<-"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
91
plot(world_sp)
92
plot(dat_stat,cex=0.2,pch=16,col=c("red"),add=TRUE)
93
#Read in sinusoidal grid and world countries
94 95

  
95
setwd(in_path)	
96
#Read in sinusoidal grid and world countries
96 97
filename<-sub(".shp","",infile_modis_grid)       #Removing the extension from file.
97 98
modis_grid<-readOGR(".", filename)     #Reading shape file using rgdal library
98
if (infile_reg_outline!=""){
99
  filename<-sub(".shp","",infile_reg_outline)   #Removing the extension from file.
100
  reg_outline<-readOGR(".", filename)
101
}
102
if (infile_reg_outline==""){
103
  reg_outline<-create_modis_tiles_region(modis_grid,list_tiles_modis) #problem...this does not 
104
  #align with extent of modis LST!!!
105
  writeOGR(reg_outline,dsn= ".",layer= paste("outline",out_region_name,"_",out_suffix,sep=""), 
106
           driver="ESRI Shapefile",overwrite_layer="TRUE")
107
}
108 99

  
109
create_modis_tiles_region<-function(modis_grid,tiles){
110
  #This functions returns a subset of tiles from the modis grdi.
111
  #Arguments: modies grid tile,list of tiles
112
  #Output: spatial grid data frame of the subset of tiles
113
  h_list<-lapply(tiles,substr,start=2,stop=3) #passing multiple arguments
114
  v_list<-lapply(tiles,substr,start=5,stop=6) #passing multiple arguments
115
  selected_tiles<-subset(subset(modis_grid,subset = h %in% as.numeric (h_list) ),
116
                         subset = v %in% as.numeric(v_list)) 
117
  return(selected_tiles)
118
}
100
#### ALL STUDY AREAS/TEST SITES
101

  
102
#c("Oregon", c("h08v04","h09v04","h08v05","h09v05"))
103
study_area_list_tiles <- vector("list",6)
104
study_area_list_tiles[[1]] <-list("Oregon", c("h08v04","h09v04"))
105
study_area_list_tiles[[2]] <-list("Venezuela",c("h10v07", "h10v08", "h11v7", "h11v08", "h12v07", "h12v08"))
106
study_area_list_tiles[[3]] <-list("Norway",c("h18v02","h18v03", "h19v02", "h19v03"))
107
study_area_list_tiles[[4]] <-list("East_Africa",c("h20v08", "h21v08", "h22v08", "h20v09", "h21v09", "h22v09", "h21v10"))
108
study_area_list_tiles[[5]] <-list("South_Africa",c("h19v11", "h20v11", "h19v12", "h20v12"))
109
study_area_list_tiles[[6]] <-list("Queensland",c("h31v10", "h31v10", "h32v10", "h30v11", "h31v11"))
110
 
111
## Create list of study area regions:
112
list_tiles<-lapply(1:length(study_area_list_tiles),function(k) study_area_list_tiles[[k]][[2]])
113
modis_reg_outlines<-lapply(list_tiles,FUN=create_modis_tiles_region,modis_sp=modis_grid) #problem...this does not 
114

  
115
#writeOGR(modis_reg_outline,dsn= ".",layer= paste("outline",out_region_name,"_",out_suffix,sep=""), 
116
#         driver="ESRI Shapefile",overwrite_layer="TRUE")
117

  
118
########## CREATE FIGURE TEST SITES ##############
119 119

  
120
dat_stat_sinusoidal <- spTransform(dat_stat,CRS(proj4string(modis_grid)))
121
world_sinusoidal <- readOGR(dsn=".",sub(".shp","",infile_countries_sinusoidal))
122

  
123
png(paste("Study_area_modis_grid",out_prefix,".png",sep=""))
124
plot(world_sinusoidal)
125
plot(dat_stat_sinusoidal,cex=0.2,pch=16,col=c("blue"),add=TRUE)
126
plot(modis_grid,add=TRUE)
127
for (k in 1:length(modis_reg_outlines)){
128
  plot(modis_reg_outlines[[k]],border=c("red"),lwd=2.5,add=TRUE)
129
}
130
title("Study area for temperature and precipitation predictions")
131
#legend
132
dev.off()
133
    
120 134
### READ IN COVARIATES FILES FOR OREGON AND MAKE IT A MULTI-BAND FILE
121 135

  
122
inlistf<-"list_files_05032012.txt"
123
lines<-read.table(paste(path,"/",inlistf,sep=""), sep=" ")                  #Column 1 contains the names of raster files
136
inlistf<-"list_files_covariates_04032013.txt"
137
lines<-read.table(paste(inlistf,sep=""), sep=" ")                  #Column 1 contains the names of raster files
124 138
inlistvar<-lines[,1]
125
inlistvar<-paste(path,"/",as.character(inlistvar),sep="")
126
covar_names<-as.character(lines[,2])                                         #Column two contains short names for covaraites
139
inlistvar<-as.character(inlistvar)
140
covar_names_OR<-as.character(lines[,2])                                         #Column two contains short names for covaraites
141

  
142
s_raster_OR<- stack(inlistvar)                                                  #Creating a stack of raster images from the list of variables.
143
layerNames(s_raster_OR)<-covar_names_OR                                            #Assigning names to the raster layers
144

  
145
aspect<-subset(s_raster_OR,"aspect")             #Select layer from stack
146
slope<-subset(s_raster_OR,"slope")             #Select layer from stack
147
distoc<-subset(s_raster_OR,"DISTOC")  
148

  
149
N<-cos(aspect*pi/180)
150
E<-sin(aspect*pi/180)
151
Nw<-sin(slope*pi/180)*cos(aspect*pi/180)   #Adding a variable to the dataframe
152
Ew<-sin(slope*pi/180)*sin(aspect*pi/180)   #Adding variable to the dataframe.
153

  
154
xy <-coordinates(slope)  #get x and y projected coordinates...
155
xy_latlon<-project(xy, CRS_interp, inv=TRUE) # find lat long for projected coordinats (or pixels...)
156

  
157
x <-init(slope,v="x")
158
y <-init(slope,v="y")
159
lon<-x
160
lat<-y
161
lon <-setValues(lon,xy_latlon[,1]) #longitude for every pixel in the processing tile/region
162
lat <-setValues(lat,xy_latlon[,2]) #latitude for every pixel in the processing tile/region
163
CANHEIGHT<-subset(s_raster_OR,"CANHEIGHT")
164
CANHEIGHT[is.na(CANHEIGHT)]<-0
165

  
166
elev<-subset(s_raster_OR,"elev")
167
elev[elev==-9999] <- NA
168

  
169
r<-stack(x,y,lon,lat,N,E,Nw,Ew,elev,slope,aspect,CANHEIGHT,distoc)
170
rnames<-c("x","y","lon","lat","N","E","N_w","E_w","elev","slope","aspect","CANHEIGHT","DISTOC")
171
s_raster<-r
172
#Add landcover layers
173
lc_names<-c("LC1","LC2","LC3","LC4","LC5","LC6","LC7","LC8","LC9","LC10")
174
lc_reg_s<-subset(s_raster_OR,lc_names)
175
#Should be a function...ok for now??
176
test<-vector("list",nlayers(lc_reg_s))
177
for (k in 1:nlayers(lc_reg_s)){
178
  LC<-raster(lc_reg_s,layer=k)             #Select layer from stack
179
  LC[is.na(LC)]<-0
180
  test[[k]]<-LC
181
}
182
#tmp_df<-freq(lc_reg_s,merge=TRUE) #check to see if it worked
183
#head(tmp_df)
184
lc_reg_s<-stack(test)
185
s_raster<-addLayer(s_raster, lc_reg_s)
186
  
187
lst_names<-c("mm_01","mm_02","mm_03","mm_04","mm_05","mm_06","mm_07","mm_08","mm_09","mm_10","mm_11","mm_12",
188
             "nobs_01","nobs_02","nobs_03","nobs_04","nobs_05","nobs_06","nobs_07","nobs_08",
189
             "nobs_09","nobs_10","nobs_11","nobs_12")
190
lst_mm_names<-c("mm_01","mm_02","mm_03","mm_04","mm_05","mm_06","mm_07","mm_08","mm_09","mm_10","mm_11","mm_12")
191
lst_mm_s<-subset(s_raster_OR,lst_mm_names)
192
lst_mm_s <- lst_mm_s - 273.16 
193
lst_nobs_names<-c("nobs_01","nobs_02","nobs_03","nobs_04","nobs_05","nobs_06","nobs_07","nobs_08",
194
                "nobs_09","nobs_10","nobs_11","nobs_12")
195
lst_nobs_s<-subset(s_raster_OR,lst_nobs_names)
196

  
197
s_raster<-addLayer(s_raster, lst_mm_s)
198
s_raster<-addLayer(s_raster, lst_nobs_s)
199
covar_names<-c(rnames,lc_names,lst_names)
200
names(s_raster)<-covar_names
201

  
202
# create mask!!! Should combine with mask of elev
203
LC10<-subset(s_raster,"LC10")
127 204

  
128
s_raster<- stack(inlistvar)                                                  #Creating a stack of raster images from the list of variables.
129
layerNames(s_raster)<-covar_names                                            #Assigning names to the raster layers
205
LC10_mask<-LC10
206
LC10_mask[is.na(LC10_mask)]<- 0
207
LC10_mask[LC10==100]<- NA
208
LC10_mask[LC10_mask<100]<- 1
209
LC10_mask[is.na(LC10_mask)]<- 0
210
mask_land_NA<-LC10_mask
211
mask_land_NA[mask_land_NA==0]<-NA
212

  
213

  
214
##### SAVE AS MULTIBAND...make this a function...
215

  
216
#list of files...
130 217
file_format<-".tif"
131
NA_val<- -999
218
NA_val<- -9999
132 219
band_order<- "BSQ"
220
var<-"TMAX"
133 221
data_name<-paste("covariates_",out_region_name,"_",sep="")
134
raster_name<-paste(data_name,var,"_",out_suffix,file_format, sep="")
222
raster_name<-paste(data_name,var,"_",out_prefix,file_format, sep="")
135 223
#writeRaster(s_raster, filename=raster_name,NAflag=-999,bylayer=FALSE,bandorder="BSQ",overwrite=TRUE)  #Writing the data in a raster file format...
136 224
#if mask
137
s_raster_m<-mask(s_raster,LC_mask,filename=raster_name,
225
#stat_val<- extract(s_raster, ghcn3)                                          #Extracting values from the raster stack for every point location in coords data frame.
226
s_raster_m<-mask(s_raster,mask_land_NA,filename=raster_name,
138 227
                 overwrite=TRUE,NAflag=NA_val,bylayer=FALSE,bandorder=band_order)
139 228
#if no mask
140 229
#writeRaster(s_raster, filename=raster_name,NAflag=-999,bylayer=FALSE,bandorder="BSQ",overwrite=TRUE)  #Writing the data in a raster file format...
141 230

  
142
#return
231
#### CREATE FIGURE MEAN DAILY AND MEAN MONTHLY: AAG 2013  ####
232

  
233
lst_md<-raster(ref_rast_name)
234
lst_mm_09<-subset(s_raster,"mm_09")
235
plot(stack(lst_md,lst_mm_09))
143 236

  
237
lst_md<-raster("mean_day001_rescaled.rst")
238
lst_md<- lst_md - 273.16
239
lst_mm_01<-subset(s_raster,"mm_01")
144 240

  
241
png(filename=paste("Comparison_daily_monthly_mean_lst",out_prefix,".png",sep=""),width=960,height=480)
242
par(mfrow=c(1,2))
243
plot(lst_md)
244
plot(interp_area,add=TRUE)
245
title("Mean for September 1")
246
plot(lst_mm_01)
247
plot(interp_area,add=TRUE)
248
title("Mean for January")
249
dev.off()
145 250

  
146 251

  
147
### SCREENING FUNCTION
252
### SCREENING FUNCTION for covariate stack and GHNCD data base to add later in the functions
148 253

  
149 254
#Screen for extreme values": this needs more thought, min and max val vary with regions
150 255
#min_val<-(-15+273.16) #if values less than -15C then screen out (note the Kelvin units that will need to be changed later in all datasets)
151 256
#r1[r1 < (min_val)]<-NA
152
s_raster<-addLayer(s_raster,LST)            #Adding current month
257
#s_raster<-addLayer(s_raster,LST)            #Adding current month
153 258

  
154 259
nel<-12
155 260
#tab_range<-data.frame(varname=character(nel),varterm=character(nel),vmin=numeric(nel),vmax=numeric(nel))
156 261
val_range<-vector("list",nel) #list of one row data.frame
157 262
val_rst<-vector("list",nel) #list of one row data.frame
158
val_range[[1]]<-data.frame(varname="lon",varterm="lon",vmin=-180,vmax=180)
159
val_range[[2]]<-data.frame(varname="lat",varterm="lat",vmin=-90,vmax=90)
160
val_range[[3]]<-data.frame(varname="ELEV_SRTM",varterm="ELEV_SRTM",vmin=0,vmax=6000)
161
val_range[[4]]<-data.frame(varname="Eastness",varterm="Eastness",vmin=-1,vmax=1)
162
val_range[[5]]<-data.frame(varname="Northness",varterm="Northness",vmin=-1,vmax=1)
163
val_range[[6]]<-data.frame(varname="Northness_w",varterm="Northness_w",vmin=-1,vmax=1)
164
val_range[[7]]<-data.frame(varname="Eastness_w",varterm="Eastness_w",vmin=-1,vmax=1)
165
val_range[[8]]<-data.frame(varname="mm_01",varterm="LST",vmin=-258.16,vmax=313.16)
166
val_range[[9]]<-data.frame(varname="DISTOC",varterm="DISTOC",vmin=-0,vmax=10000000)
167
val_range[[10]]<-data.frame(varname="LC1",varterm="LC1",vmin=0,vmax=100)
168
val_range[[11]]<-data.frame(varname="LC3",varterm="LC3",vmin=0,vmax=100)
169
val_range[[12]]<-data.frame(varname="slope",varterm="slope",vmin=0,vmax=90)
263
val_range[[1]]<-data.frame(varname="lon",vmin=-180,vmax=180)
264
val_range[[2]]<-data.frame(varname="lat",vmin=-90,vmax=90)
265
val_range[[3]]<-data.frame(varname="N",vmin=-1,vmax=1)
266
val_range[[4]]<-data.frame(varname="E",vmin=-1,vmax=1)
267
val_range[[5]]<-data.frame(varname="N_w",vmin=-1,vmax=1)
268
val_range[[6]]<-data.frame(varname="E_w",vmin=-1,vmax=1)
269
val_range[[7]]<-data.frame(varname="elev",vmin=0,vmax=6000)
270
val_range[[8]]<-data.frame(varname="slope",varterm="slope",vmin=0,vmax=90)
271
val_range[[9]]<-data.frame(varname="aspect",varterm="aspect",vmin=0,vmax=360)
272
val_range[[10]]<-data.frame(varname="DISTOC",vmin=-0,vmax=10000000)
273
val_range[[11]]<-data.frame(varname="CANHEIGHT",vmin=0,vmax=255)
274
val_range[[12]]<-data.frame(varname="LC1",vmin=0,vmax=100)
275
val_range[[13]]<-data.frame(varname="LC3",vmin=0,vmax=100)
276
val_range[[14]]<-data.frame(varname="mm_01",vmin=-15,vmax=50)
277
val_range[[15]]<-data.frame(varname="mm_02",vmin=-15,vmax=50)
278
val_range[[16]]<-data.frame(varname="mm_03",vmin=-15,vmax=50)
279
val_range[[17]]<-data.frame(varname="mm_04",vmin=-15,vmax=50)
280
val_range[[18]]<-data.frame(varname="mm_05",vmin=-15,vmax=50)
281
val_range[[19]]<-data.frame(varname="mm_06",vmin=-15,vmax=50)
282
val_range[[20]]<-data.frame(varname="mm_07",vmin=-15,vmax=50)
283
val_range[[21]]<-data.frame(varname="mm_08",vmin=-15,vmax=50)
284
val_range[[22]]<-data.frame(varname="mm_09",vmin=-15,vmax=50)
285
val_range[[23]]<-data.frame(varname="mm_10",vmin=-15,vmax=50)
286
val_range[[24]]<-data.frame(varname="mm_11",vmin=-15,vmax=50)
287
val_range[[25]]<-data.frame(varname="mm_12",vmin=-15,vmax=50)
288

  
170 289
tab_range<-do.call(rbind,val_range)
290

  
171 291
#pos<-match("ELEV_SRTM",layerNames(s_raster)) #Find column with the current month for instance mm12
172 292
#ELEV_SRTM<-raster(s_raster,pos)
173
for (k in 1:length(val_range)){
174
  avl<-c(-Inf,tab_range$vmin[k],NA, tab_range$vmax[k],+Inf,NA)   #This creates a input vector...val 1 are -9999, 2 neg, 3 positive
175
  rclmat<-matrix(avl,ncol=3,byrow=TRUE)
176
  s_raster_r<-raster(s_raster_f,match(tab_range$varterm[k],layerNames(s_raster_f)))
177
  s_raster_r<-reclass(s_raster_r,rclmat)  #Loss of layer names when using reclass
178
  layerNames(s_raster_r)<-tab_range$varterm[k]
179
  val_rst[[k]]<-s_raster_r
293

  
294
screening_val_covariates_fun<-function(tab_range,r_stack){
295
  #Screening for raster stack
296
  #
297
  for (k in 1:nrow(tab_range)){
298
    avl<-c(-Inf,tab_range$vmin[k],NA, tab_range$vmax[k],+Inf,NA)   #This creates a input vector...val 1 are -9999, 2 neg, 3 positive
299
    rclmat<-matrix(avl,ncol=3,byrow=TRUE)
300
    #s_raster_r<-raster(r_stack,match(tab_range$varterm[k],names(r_stack))) #select relevant layer from stack
301
    s_raster_r<-raster(r_stack,match(tab_range$varname[k],names(r_stack)))
302
    s_raster_r<-reclass(s_raster_r,rclmat)  #now reclass values 
303
    r_stack<-dropLayer(r_stack,"N")
304
    names(s_raster_r)<-tab_range$varname[k] #Loss of layer names when using reclass
305
    val_rst[[k]]<-s_raster_r
306
  }
307
  s_rst_m<-stack(val_rst) #This a raster stack with valid range of values
308
  r_stack<-addLayer(r_stack,s_rst_m) #add back layers that were screened out
309
  return(r_stack)
180 310
}
181
s_rst_m<-stack(val_rst) #This a raster stack with valid range of values
182 311

  
312
#### ADD SCREENING FUNCTION FOR GHCND extracted!!!
183 313

  
314
#Remove NA for LC and CANHEIGHT
315
#ghcn$LC1[is.na(ghcn$LC1)]<-0
316
#ghcn$LC3[is.na(ghcn$LC3)]<-0
317
#ghcn$CANHEIGHT[is.na(ghcn$CANHEIGHT)]<-0
318
#ghcn$LC4[is.na(ghcn$LC4)]<-0
319
#ghcn$LC6[is.na(ghcn$LC6)]<-0
320
##ghcn$ELEV_SRTM[ghcn$ELEV_SRTM==-9999]<-NA
321
#dst<-subset(dst,dst$TMax>-15 & dst$TMax<40)
322
#dst<-subset(dst,dst$ELEV_SRTM>0) #This will drop two stations...or 24 rows

Also available in: Unified diff