Project

General

Profile

Download (14.1 KB) Statistics
| Branch: | Revision:
1
###################################################################################
2
###  R code to aquire and process MOD06_L2 cloud data from the MODIS platform
3

    
4

    
5
## connect to server of choice
6
#system("ssh litoria")
7
#R
8

    
9
library(sp)
10
library(rgdal)
11
library(reshape)
12
library(ncdf4)
13
library(geosphere)
14
library(rgeos)
15
library(multicore)
16
library(raster)
17
library(lattice)
18
library(rgl)
19
library(hdf5)
20

    
21
X11.options(type="Xlib")
22
ncores=20  #number of threads to use
23

    
24
setwd("/home/adamw/personal/projects/interp")
25
setwd("/home/adamw/acrobates/projects/interp")
26

    
27
roi=readOGR("data/regions/Test_sites/Oregon.shp","Oregon")
28
roi=spTransform(roi,CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0"))
29

    
30
### Downloading data from LAADSWEB
31
# subset by geographic area of interest
32
# subset: 40-47, -115--125
33

    
34
## download data from ftp site.  Unfortunately the selection has to be selected using the website and orders downloaded via ftp.
35

    
36
system("wget -r --retr-symlinks ftp://ladsweb.nascom.nasa.gov/orders/500676499/ -P /home/adamw/acrobates/projects/interp/data/modis/MOD06_L2_hdf")
37

    
38

    
39
gdir="output/"
40
datadir="data/modis/MOD06_L2_hdf"
41
outdir="data/modis/MOD06_L2_nc"
42
  
43
fs=data.frame(
44
  path=list.files(datadir,full=T,recursive=T,pattern="hdf"),
45
  file=basename(list.files(datadir,full=F,recursive=T,pattern="hdf")))
46
fs$date=as.Date(substr(fs$file,11,17),"%Y%j")
47
fs$time=substr(fs$file,19,22)
48
fs$datetime=as.POSIXct(strptime(paste(substr(fs$file,11,17),substr(fs$file,19,22)), '%Y%j %H%M'))
49
fs$path=as.character(fs$path)
50
fs$file=as.character(fs$file)
51

    
52
## output ROI
53
#get bounding box of region in m
54
ge=SpatialPoints(data.frame(lon=c(-125,-115),lat=c(40,47)))
55
projection(ge)=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
56
ge2=spTransform(ge, CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0"))
57

    
58

    
59
## vars
60
vars=paste(c(
61
  "Cloud_Effective_Radius",
62
  "Cloud_Effective_Radius_Uncertainty",
63
  "Cloud_Optical_Thickness",
64
  "Cloud_Optical_Thickness_Uncertainty",
65
  "Cloud_Water_Path",
66
  "Cloud_Water_Path_Uncertainty",
67
  "Cloud_Phase_Optical_Properties",
68
  "Cloud_Multi_Layer_Flag",
69
  "Cloud_Mask_1km",
70
  "Quality_Assurance_1km"))
71

    
72
### Installation of hegtool
73
## needed 32-bit libraries and java for program to install correctly
74

    
75
#system(paste("ncl_convert2nc ",f," -i ",hdfdir," -o ",outdir," -v ",vars," -nc4c -l -cl 1 -B ",sep=""))
76
#system(paste("h4toh5 ",hdfdir,"/",f," ",outdir,"/",f,sep=""))
77
# system(paste("hegtool -h ",fs$path[1],sep=""))
78

    
79

    
80
#### Function to generate hegtool parameter file for multi-band HDF-EOS file
81
swath2grid=function(i=1,files,vars=vars,outdir,upleft="47 -125",lowright="41 -115"){
82
  file=fs$path[i]
83
  tempfile=paste(tempdir(),"/",fs$file[i],sep="")
84
  outfile=sub("hdf$","nc",paste(outdir,"/",fs$file[i],sep=""))
85
  date=fs$date[1]
86
  origin=as.POSIXct("1970-01-01 00:00:00",tz="GMT")
87
### First write the parameter file (careful, heg is very finicky!)
88
  hdr=paste("NUM_RUNS = ",length(vars),"|MULTI_BAND_HDFEOS:",length(vars),sep="")
89
  grp=paste("
90
BEGIN
91
INPUT_FILENAME=",file,"
92
OBJECT_NAME=mod06
93
FIELD_NAME=",vars,"|
94
BAND_NUMBER = 1
95
OUTPUT_PIXEL_SIZE_X=1000
96
OUTPUT_PIXEL_SIZE_Y=1000
97
SPATIAL_SUBSET_UL_CORNER = ( ",upleft," )
98
SPATIAL_SUBSET_LR_CORNER = ( ",lowright," )
99
RESAMPLING_TYPE = NN
100
OUTPUT_PROJECTION_TYPE = SIN
101
ELLIPSOID_CODE = WGS84
102
OUTPUT_PROJECTION_PARAMETERS = ( 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  )
103
OUTPUT_TYPE = HDFEOS
104
OUTPUT_FILENAME = ",tempfile,"
105
END
106

    
107

    
108
",sep="")
109
  ## write it to a file
110
  cat(c(hdr,grp)    , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
111
  ## now run the swath2grid tool  - must be run as root (argh!)!
112
  if(file.exists(tempfile)) file.remove(tempfile)
113
  log=system(paste("sudo MRTDATADIR=\"/usr/local/heg/data\" ",
114
    "PGSHOME=/usr/local/heg/TOOLKIT_MTD PWD=/home/adamw /usr/local/heg/bin/swtif -p ",
115
    paste(tempdir(),"/",basename(file),"_MODparms.txt -d",sep=""),sep=""),intern=T)
116
#  system(paste("h5dump -H ",tempdir(),"/",basename(file),sep=""))
117

    
118
#    log=system(paste("swtif -p ",paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""),sep=""),intern=T)
119
  ## convert it to netcdf and clean up
120
  system(paste("NCARG_ROOT=\"/usr/local/ncl_ncarg-6.0.0\" ncl_convert2nc ",
121
               basename(tempfile)," -i ",tempdir()," -o ",tempdir()," -B ",sep=""))
122
  ncfile1=paste(tempdir(),"/",sub("hdf","nc",basename(file)),sep="")
123
    ## add time variable
124
  print("Adding time dimension")
125
  system(paste("ncecat -O -u time ",ncfile1,outfile))
126
  system(paste("ncap2 -s \'time[time]=",
127
               as.numeric(difftime(fs$datetime[i],origin,units="mins")),"\'  ",outfile,sep=""))
128

    
129
 ######################################################################################
130
  print("Updating netCDF dimensions")
131
  ## rename dimension variables
132
  system(paste("ncrename -d YDim_mod06,y -d XDim_mod06,x ",outfile))
133
  system(paste("ncap2 -s \'x[x]=0;y[y]=0\' ",outfile))
134
  system(paste("ncap2 -s \'lat[x,y]=0;lon[x,y]=0\' ",outfile))
135
  system(paste("ncap2 -s \'sinusoidal=0\' ",outfile))
136
  
137
  nc=nc_open(outfile,write=T)
138
### Get corner coordinates and convert to cell centers
139
  ncd=system(paste("ncdump -h ",outfile),intern=T)
140
  UL= as.numeric(do.call(c,strsplit(gsub("[a-z]|[A-Z]|[\\]|[\t]|[\"]|[=]|[(]|[)]|","",
141
    ncd[grep("UpperLeft",ncd)]),",")))+c(500,-500)
142
  LR= as.numeric(do.call(c,strsplit(gsub("[a-z]|[A-Z]|[\\]|[\t]|[\"]|[=]|[(]|[)]|","",
143
    ncd[grep("LowerRight",ncd)]),",")))+c(-500,500)
144
  
145
  xvar=seq(UL[1],LR[1],by=1000)
146
  yvar=seq(UL[2],LR[2],by=-1000)
147
  ncvar_put(nc,"x",vals=xvar)
148
  ncvar_put(nc,"y",vals=yvar)
149

    
150
  
151
  ## add lat-lon grid
152
  grid=expand.grid(x=xvar,y=yvar)
153
  coordinates(grid)=c("x","y")
154
  projection(grid)=CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0")
155
  grid2=spTransform(grid,CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
156
  grid=SpatialPointsDataFrame(grid,data=cbind.data.frame(coordinates(grid),coordinates(grid2)))
157
  gridded(grid)=T
158
  fullgrid(grid)=T
159
  colnames(grid@data)=c("x","y","lon","lat")
160

    
161
  xlon=as.matrix(grid["lon"])
162
  ylat=as.matrix(grid["lat"])
163

    
164
  ncvar_put(nc,"lon",vals=xlon)
165
  ncvar_put(nc,"lat",vals=ylat)
166

    
167
  nc_close(nc)
168

    
169
  ## update attributes
170
  for(v in c(vars[!grepl("Mask|Quality",vars)],paste(vars[grepl("Mask|Quality",vars)],"_0",sep=""))) {
171
    print(v)
172
    system(paste("ncatted -a coordinates,",v,",o,c,\"lat lon\" ",outfile,sep=""))
173
    system(paste("ncatted -a grid_mapping,",v,",o,c,\"sinusoidal\" ",outfile,sep=""))
174
  }
175
  
176
  system(paste("ncatted -a units,time,o,c,\"Minutes since ",origin,"\" ",outfile))
177
  system(paste("ncatted -a long_name,time,o,c,\"time\"",outfile))
178

    
179
  system(paste("ncatted -a units,y,o,c,\"m\" ",outfile))
180
  system(paste("ncatted -a long_name,y,o,c,\"y coordinate of projection\" ",outfile))
181
  system(paste("ncatted -a standard_name,y,o,c,\"projection_y_coordinate\" ",outfile))
182

    
183
  system(paste("ncatted -a units,x,o,c,\"m\" ",outfile))
184
  system(paste("ncatted -a long_name,x,o,c,\"x coordinate of projection\" ",outfile))
185
  system(paste("ncatted -a standard_name,x,o,c,\"projection_x_coordinate\" ",outfile))
186

    
187
  ## grid attributes
188
  system(paste("ncatted -a units,lat,o,c,\"degrees_north\" ",outfile))
189
  system(paste("ncatted -a long_name,lat,o,c,\"latitude coordinate\" ",outfile))
190
  system(paste("ncatted -a standard_name,lat,o,c,\"latitude\" ",outfile))
191

    
192
  system(paste("ncatted -a units,lon,o,c,\"degrees_east\" ",outfile))
193
  system(paste("ncatted -a long_name,lon,o,c,\"longitude coordinate\" ",outfile))
194
  system(paste("ncatted -a standard_name,lon,o,c,\"longitude\" ",outfile))
195

    
196
   system(paste("ncatted -a grid_mapping_name,sinusoidal,o,c,\"sinusoidal\" ",outfile))
197
  system(paste("ncatted -a standard_parallel,sinusoidal,o,c,\"0\" ",outfile))
198
  system(paste("ncatted -a longitude_of_central_meridian,sinusoidal,o,c,\"0\" ",outfile))
199
  system(paste("ncatted -a latitude_of_central_meridian,sinusoidal,o,c,\"0\" ",outfile))
200

    
201
  system(paste("cdo griddes ",outfile," > grid.txt"))
202
  system(paste("cdo mergegrid",outfile,
203
               "data/modis/MOD06_L2_nc/MOD06_L2.A2006001.2025.051.2010304104117.gscs_000500676714.nc ",
204
               "data/modis/MOD06_L2_nc/test.nc",sep=" "))
205
  
206
  print(paste("Finished ", file))
207
}
208

    
209

    
210

    
211
i=100
212

    
213

    
214
#### Run the gridding procedure
215

    
216
for(fi in 1:nrow(fs))
217
swath2grid(fi,vars=vars,files=fs,outdir=outdir,upleft="47 -125",lowright="40 -115")
218

    
219
### get grid from file the covers the region
220
system(paste("cdo griddes",paste(list.files(outdir,full=T)[1],collapse=" ")," > data/modis/MOD06L2_grid.txt"))
221

    
222

    
223
#### Merge the files
224
system(paste("cdo mergetime ",paste("-remapnn,data/modis/MOD06L2_grid.txt",list.files(outdir,full=T),collapse=" "),"
225
data/modis/MOD06L2.nc"))
226

    
227
#get bounding box of region in m
228
ge=SpatialPoints(data.frame(lon=c(-125,-115),lat=c(40,47)))
229
projection(ge)=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
230
ge2=spTransform(ge, CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0"))
231

    
232
system(paste("ncks -d x,-10674232,-8746440 -d y,4429529,5207247 ", paste(list.files(outdir,full=T)[1],collapse=" "),"data/modis/test.nc")) 
233

    
234

    
235

    
236
cat(paste("
237
               gridtype=curvilinear
238
               gridsize=
239
               xsize=2157
240
               ysize=1037
241

    
242
               "),file="data/modis/grid.txt")
243

    
244
#system(paste("cdo -f grb  ",list.files(outdir,full=T)[1]," data/modis/test.grb"))
245

    
246
fs2=list.files(outdir,full=T)
247
d=raster(fs2[3],varname=vars[3])
248
projection(d)=CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0")
249
plot(d)
250

    
251

    
252

    
253

    
254
### subset to particular variables and drop uncertainties
255
f=fs[grep(vars[3],fs$file),]
256
f=f[!grepl("Uncertainty",f$file),]
257

    
258
getextent=function(file=f$file[1]) {
259
ext=extent(raster(file))
260
data.frame(file=file,xmin=attr(ext,"xmin"),xmax=attr(ext,"xmax"),ymin=attr(ext,"ymin"),ymax=attr(ext,"ymax"))
261
}
262

    
263
### some extents don't line up, find which ones...
264
ext=do.call(rbind.data.frame,mclapply(f$path,getextent))
265
f[which(ext$xmax!=ext$xmax[1]),]
266
f[which(ext$ymin!=ext$ymin[1]),]
267

    
268
### get  extent of first image
269
ext1=extent(raster(f$path[1]))
270
### generate brick of all images
271
d=brick(lapply(f$path, function(i) {print(i) crop(raster(i),ext1)}))
272

    
273

    
274
## rescale data and identify NAs
275
NAvalue(d)=-9999
276
d=d*0.009999999776482582
277

    
278
plot(d)
279

    
280
## calculate overall mean
281
dm=mean(d,na.rm=T)
282

    
283
## plot it
284
X11.options(type="Xlib")
285

    
286
pdf("output/MOD06_mean.pdf",width=1000,height=600)
287
plot(d)
288
plot(roi,add=T)
289
dev.off()
290

    
291

    
292

    
293

    
294

    
295

    
296

    
297

    
298

    
299

    
300

    
301

    
302

    
303
#### load the functions
304
source("code/GHCN_functions.r")
305

    
306

    
307

    
308

    
309

    
310
#################################################
311
#### Download Data
312
dir.create("data/lst")
313
ftpsite="atlas.nceas.ucsb.edu:/home/parmentier/data_Oregon_stations/"
314
system(paste("scp -r wilson@",ftpsite,"mean_month* data/lst ",sep=""))
315

    
316
lst=brick(as.list(list.files("data/lst/",pattern=".*rescaled[.]rst",full=T)[c(4:12,1:3)]))
317
projection(lst)=CRS("+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 +datum=NAD83 +units=m +no_defs ")
318
lst=lst-272.15
319

    
320

    
321
#################################################
322
### Load PRISM
323
prism=brick("data/prism/prism_tmax.nc")
324
prism=projectRaster(prism,lst)
325

    
326
prism2=as(prism,"SpatialGridDataFrame");colnames(prism2@data)=paste("X",1:12,sep="")
327
prism2$source="prism"
328
prism2@data[c("lon","lat")]=coordinates(prism2)
329

    
330
lst2=as(lst,"SpatialGridDataFrame");colnames(lst2@data)=paste("X",1:12,sep="")
331
lst2$source="modis"
332
lst2@data[c("lon","lat")]=coordinates(lst2)
333

    
334
d=rbind.data.frame(melt(prism2@data,id.vars=c("source","lat","lon")),melt(lst2@data,id.vars=c("source","lat","lon")))
335
d$source=as.factor(d$source)
336
colnames(d)[grep("variable",colnames(d))]="month"
337
levels(d$month)=month.name
338
d=d[!is.na(d$value),]
339

    
340
d2=cast(d,lat+lon+month~source); gc()
341
d2$modis[d2$modis<(-50)]=NA
342

    
343

    
344

    
345

    
346
plot(subset(lst,1),col=rev(heat.colors(20)))
347

    
348

    
349

    
350
#### Explore prism-LST relationship (and land cover!?!)
351

    
352
png(width=1024,height=768,file="LSTvsPRISM.png")
353
xyplot(modis~prism|month,data=d2,panel=function(x,y,subscripts){
354
  panel.xyplot(x,y,cex=.2,pch=16,col="black")
355
  lm1=lm(y~x)
356
  panel.abline(lm1)
357
  panel.abline(0,1,col="red")
358
  panel.text(-0,40,paste("R2=",round(summary(lm1)$r.squared,2)))
359
},ylab="MODIS Daytime LST (C)",xlab="PRISM Maximum Temperature (C)",
360
sub="Red line is y=x, black line is regression")
361
dev.off()
362

    
363

    
364
### Bunch of junk below here!
365

    
366

    
367
#### Perspective plot
368
open3d()
369

    
370

    
371
### load data to show some points
372
load("stroi.Rdata")
373
load("data/ghcn/roi_ghcn.Rdata")
374
d2=d[d$date=="2010-01-01"&d$variable=="tmax",]
375

    
376
r=extent(212836,234693,320614,367250)
377
z=as.matrix(raster(crop(lst,r),layer=1))
378

    
379
x <- 1:nrow(z) 
380
y <- 1:ncol(z) 
381

    
382

    
383
ncol=50
384
colorlut <- heat.colors(ncol,alpha=0) # height color lookup table
385
#col <- colorlut[ z-min(z)+1 ] # assign colors to heights for each point
386
col <- colorlut[trunc((z/max(z))*(ncol-1))+1] # assign colors to heights for each point
387

    
388

    
389
rgl.surface(x, y, z, color=col, alpha=0.75, back="lines")
390
rgl.points()
391

    
392
#### 2d example
393
n=100
394
xlim=c(-2,3)
395
x=seq(xlim[1],xlim[2],length=n)
396
e=rnorm(n,0,.5)
397

    
398
### climate function
399
yclimate<-function(x) x^4-x^3-7*x^2+1.2*x+15+(1.2*sin(x*.5))+(1*cos(x*5))
400
### daily weather function
401
yweather<-function(x) yclimate(x)+2.5*x+.3*x^3
402

    
403
y1=yclimate(x)
404
y2=yweather(x)
405

    
406
#points
407
s=c(-1.5,-.2,1.4,2.5)
408
s1=yclimate(s)
409
s2=yweather(s)
410

    
411
png(width=1024,height=768,file="anomalyapproach_%d.png",pointsize=28)
412
for(i in 1:6){
413
par(mfrow=c(2,1),mar=c(0,5,4,1))
414
plot(y2~x,type="l",xaxt="n",xlab="Space",ylab="Temperature",las=1,ylim=c(-9,22),
415
     yaxp=c(0,20,1),col="transparent")
416
if(i<5) mtext("Space",1)
417
## points
418
if(i>=1) {
419
  points(s,s2,pch=16,col="blue")
420
  text(0.1,11,"Station data",col="blue")
421
}
422
if(i>=2) {
423
  lines(y2~x,lwd=2)
424
  points(s,s2,pch=16,col="blue") #put points back on top
425
  text(xlim[1]+.5,-3,"Weather")
426
}
427
if(i>=3) {
428
  lines(y1~x,col="darkgreen",lwd=2)
429
  text(xlim[1]+.5,10,"Climate",col="darkgreen")
430
}
431
if(i>=4) segments(s,s2,s,s1,col="blue",lwd=2)
432
### anomalies
433
if(i>=5) {
434
par(mar=c(4,5,1,1))
435
plot(I(y2-y1)~x,type="l",xaxt="n",xlab="Space",
436
     ylab="Temperature Anomaly \n (Weather-Climate)",las=1,ylim=c(-9,20),
437
     yaxp=c(0,20,1),col="transparent")
438
## points
439
points(s,s2-s1,pch=16,col="blue")
440
abline(h=0,col="grey",lwd=2)
441
segments(s,0,s,s2-s1,col="blue",lwd=2)
442
}
443
if(i>=6) lines(I(y2-y1)~x,lwd=2)
444
}
445
dev.off()
446

    
447

    
448

    
449
##########################################################
450
#### Identify region of interest
451

    
452
### develop in region of interest spatial polygon
453
roi=readOGR("data/boundaries/statesp020.shp","statesp020")
454
proj4string(roi)=CRS("+proj=longlat +datum=WGS84")
455
roi=roi[roi$STATE=="Oregon",]
456
## buffer region of interest to include surrounding stations (in km)
457
roib=bufferroi(roi,distance=100)
458

    
(2-2/7)