Project

General

Profile

« Previous | Next » 

Revision 147da66d

Added by Adam M. Wilson over 12 years ago

  • ID 147da66dc5e403a026bd042b300a98027c6b4df7

Adding some MOD06 (cloud product) processing routines. Still a work in progress

View differences:

climate/procedures/MOD06_L2_data_compile.r
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
library(spgrass6)
21

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

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

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

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

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

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

  
39

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

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

  
61

  
62
## vars
63
vars=as.data.frame(matrix(c(
64
  "Cloud_Effective_Radius","CER",
65
  "Cloud_Effective_Radius_Uncertainty","CERU",
66
  "Cloud_Optical_Thickness","COT",
67
  "Cloud_Optical_Thickness_Uncertainty","COTU",
68
  "Cloud_Water_Path","CWP",
69
  "Cloud_Water_Path_Uncertainty","CWPU",
70
  "Cloud_Phase_Optical_Properties","CPOP",
71
  "Cloud_Multi_Layer_Flag","CMLF",
72
  "Cloud_Mask_1km","CM1",
73
  "Quality_Assurance_1km","QA"),
74
  byrow=T,ncol=2,dimnames=list(1:10,c("variable","varid"))))
75

  
76

  
77
### Installation of hegtool
78
## needed 32-bit libraries and java for program to install correctly
79

  
80
# system(paste("hegtool -h ",fs$path[1],sep=""))
81

  
82

  
83
#### Function to generate hegtool parameter file for multi-band HDF-EOS file
84
swath2grid=function(i=1,files,vars=vars,outdir,upleft="47 -125",lowright="41 -115"){
85
  file=fs$path[i]
86
  print(paste("Starting file",basename(file)))
87
  outfile=paste(outdir,"/",fs$file[i],sep="")
88
#  date=fs$date[1]
89
#  origin=as.POSIXct("1970-01-01 00:00:00",tz="GMT")
90
### First write the parameter file (careful, heg is very finicky!)
91
  hdr=paste("NUM_RUNS = ",length(vars),"|MULTI_BAND_HDFEOS:",length(vars),sep="")
92
  grp=paste("
93
BEGIN
94
INPUT_FILENAME=",file,"
95
OBJECT_NAME=mod06
96
FIELD_NAME=",vars,"|
97
BAND_NUMBER = 1
98
OUTPUT_PIXEL_SIZE_X=1000
99
OUTPUT_PIXEL_SIZE_Y=1000
100
SPATIAL_SUBSET_UL_CORNER = ( ",upleft," )
101
SPATIAL_SUBSET_LR_CORNER = ( ",lowright," )
102
#RESAMPLING_TYPE =",ifelse(grepl("Flag|Mask|Quality",vars$variable),"NN","BICUBIC"),"
103
RESAMPLING_TYPE =NN
104
OUTPUT_PROJECTION_TYPE = SIN
105
ELLIPSOID_CODE = WGS84
106
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  )
107
OUTPUT_TYPE = HDFEOS
108
OUTPUT_FILENAME = ",outfile,"
109
END
110

  
111

  
112
",sep="")
113
  ## if any remnants from previous runs remain, delete them
114
  if(length(list.files(tempdir(),pattern=basename(file)))>0)
115
    file.remove(list.files(tempdir(),pattern=basename(file),full=T))
116
  ## write it to a file
117
  cat(c(hdr,grp)    , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
118
  ## now run the swath2grid tool  - must be run as root (argh!)!
119
  ## write the tiff file
120
  log=system(paste("sudo MRTDATADIR=/usr/local/heg/data ",
121
    "PGSHOME=/usr/local/heg/TOOLKIT_MTD PWD=/home/adamw /usr/local/heg/bin/swtif -p ",
122
    paste(tempdir(),"/",basename(file),"_MODparms.txt -d",sep=""),sep=""),intern=T)
123
      print(paste("Finished ", file))
124
}
125

  
126

  
127
### update fs with completed files
128
fs$complete=fs$file%in%list.files(outdir,pattern="hdf$")
129
table(fs$complete)
130

  
131
#### Run the gridding procedure
132

  
133
system("sudo ls")
134

  
135
mclapply(which(!fs$complete),function(fi){
136
  swath2grid(fi,vars=vars$variable,files=fs,
137
             outdir=outdir,
138
             upleft="47 -125",lowright="40 -115")},
139
         mc.cores=24)
140

  
141

  
142
##############################################################
143
### Import to GRASS for processing
144

  
145
fs$grass=paste(fs$month,fs$year,fs$file,sep="_")
146
td=readGDAL(paste("HDF4_EOS:EOS_GRID:\"",outdir,"/",fs$file[1],"\":mod06:Cloud_Mask_1km_0",sep=""))
147

  
148
## fucntion to convert binary to decimal to assist in identifying correct values
149
b2d=function(x) sum(x * 2^(rev(seq_along(x)) - 1)) #http://tolstoy.newcastle.edu.au/R/e2/help/07/02/10596.html
150
## for example:
151
b2d(c(T,T))
152

  
153
### create (or connect to) grass location
154
gisDbase="/media/data/grassdata"
155
gisLocation="oregon"
156
gisMapset="mod06"
157

  
158
initGRASS(gisBase="/usr/lib/grass64",gisDbase=gisDbase,SG=td,override=T,
159
          location=gisLocation,mapset=gisMapset)
160

  
161

  
162
## update projection (for some reason the datum doesn't get identified from the HDF files
163
#cat("name: Sinusoidal (Sanson-Flamsteed)
164
#proj: sinu
165
#datum: wgs84
166
#ellps: wgs84
167
#lon_0: 0
168
#x_0: 0
169
#y_0: 0
170
#towgs84: 0,0,0,0,0,0,0
171
#no_defs: defined",file=paste(gisDbase,"/",gisLocation,"/PERMANENT/PROJ_INFO",sep=""))
172
## update PROJ_UNITS
173
#cat("unit: Meter
174
#units: Meters
175
#meters: 1",file=paste(gisDbase,"/",gisLocation,"/PERMANENT/PROJ_UNITS",sep=""))
176
#system("g.proj -d")
177

  
178
i=1
179
file=paste(outdir,"/",fs$file[1],sep="")
180

  
181

  
182
loadcloud<-function(file){
183
  ## Cloud Mask
184
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Mask_1km_0",sep=""),
185
            output="CM1",flags=c("overwrite","o"))
186
   system("g.region rast=CM1")
187

  
188
   ## extract cloudy and 'confidently clear' pixels
189
   system(paste("r.mapcalc <<EOF
190
                CM_cloud=  ((CM1 / 2^0) % 2) == 1  &&  ((CM1 / 2^1) % 2^2) == 0
191
                CM_clear=  ((CM1 / 2^0) % 2) == 1  &&  ((CM1 / 2^1) % 2^2) == 3
192
EOF"))
193
   
194
   ## QA
195
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Quality_Assurance_1km_0",sep=""),
196
             output="QA",flags=c("overwrite","o"))
197
   ## QA_CER
198
   system(paste("r.mapcalc <<EOF
199
                 QA_COT=   ((QA / 2^0) % 2^1 )==1
200
                 QA_COT2=  ((QA / 2^1) % 2^2 )==3
201
                 QA_COT3=  ((QA / 2^3) % 2^2 )==0
202
                 QA_CER=   ((QA / 2^5) % 2^1 )==1
203
                 QA_CER2=  ((QA / 2^6) % 2^2 )==3
204
EOF")) 
205
#                 QA_CWP=   ((QA / 2^8) % 2^1 )==1
206
#                 QA_CWP2=  ((QA / 2^9) % 2^2 )==3
207

  
208
   ## Optical Thickness
209
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Optical_Thickness",sep=""),
210
            output="COT",
211
            title="cloud_effective_radius",
212
            flags=c("overwrite","o")) ; print("")
213
   execGRASS("r.null",map="COT",setnull="-9999")
214
   ## keep only positive COT values where quality is 'useful' and 'very good' & scale to real units
215
   system(paste("r.mapcalc \"COT=if(QA_COT&&QA_COT2&&QA_COT3&&COT>=0,COT*0.009999999776482582,null())\""))   
216
   ## set COT to 0 in clear-sky pixels
217
   system(paste("r.mapcalc \"COT2=if(CM_clear,COT,0)\""))   
218
   
219
   ## Effective radius
220
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Effective_Radius",sep=""),
221
            output="CER",
222
            title="cloud_effective_radius",
223
            flags=c("overwrite","o")) ; print("")
224
   execGRASS("r.null",map="CER",setnull="-9999")
225
   ## keep only positive CER values where quality is 'useful' and 'very good' & scale to real units
226
   system(paste("r.mapcalc \"CER=if(QA_CER&&QA_CER2&&CER>=0,CER*0.009999999776482582,null())\""))   
227

  
228
   ## Cloud Water Path
229
#   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Water_Path",sep=""),
230
#            output="CWP",title="cloud_water_path",
231
#            flags=c("overwrite","o")) ; print("")
232
#   execGRASS("r.null",map="CWP",setnull="-9999")
233
#   ## keep only positive CWP values where quality is 'useful' and 'very good' & scale to real units
234
#   system(paste("r.mapcalc \"CWP=if(QA_CWP&&QA_CWP2,CWP,null())\""))   
235

  
236
   
237
 } ;
238

  
239
## unlock the grass database
240
unlink_.gislock()
241

  
242

  
243

  
244
  d=readRAST6("COT")
245
  d$CER=readRAST6("CER")$CER
246
plot(COT~CER,data=d@data)
247
summary(lm(COT~CER,data=d@data))
248

  
249

  
250

  
251

  
252
# read in data as single spatialgrid
253
ms=c("01","02","03","04","05","06","07","08","09","10","11","12")
254
for (m in ms){
255
  d=readRAST6(fs$grass[1])
256
  projection(d)=projection(td)
257
  d@data=as.data.frame(do.call(cbind,mclapply(which(fs$month==m),function(i){
258
    print(fs$date[i])
259
    readRAST6(fs$grass[i])@data[,1]
260
    })))
261
  d=brick(d)
262
  gc()
263
  assign(paste("m",m,sep="_"),d)
264
}
265

  
266
save(paste("m",m,sep="_"),file="output/MOD06.Rdata")
267

  
268
## replace missings with 0 (because they mean no clouds)
269
db2=d
270
db2[is.na(db2)]=0
271

  
272

  
273
md=mean(db,na.rm=T)
274
mn=sum(!is.na(db))
275

  
276

  
277
md2=mean(db2,na.rm=T)
278

  
279

  
280
# Histogram equalization stretch
281
eqstretch<-function(img){
282
  ecdf<-ecdf(getValues(img))
283
  return(calc(img,fun=function(x) ecdf(x)*255))
284
}
285

  
286
ncol=100
287
plot(md,col=rainbow(ncol),breaks=quantile(as.matrix(md),seq(0,1,len=ncol-1),na.rm=T))
288

  
289
str(d)
290
plot(brick(d))
291

  
292

  
293

  
294

  
295

  
296

  
297

  
298
#################################################################
299
### start grass to process the files
300

  
301
#get bounding box of region in m
302
ge=SpatialPoints(data.frame(lon=c(-125,-115),lat=c(40,47)))
303
projection(ge)=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
304
ge2=spTransform(ge, CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0")); ge2
305

  
306

  
307

  
308
system("grass -text /media/data/grassdata/oregon/mod06")
309

  
310
### import variables one at a time
311
basedir=/home/adamw/acrobates/projects/interp/data/modis/MOD06_L2_tif
312

  
313
## parse the file names
314
fs=`ls data/modis/MOD06_L2_tif | grep tif$`
315
echo `echo $fs | wc -w` files to process
316

  
317
## example file
318
f=MOD06_L2.A2000062.1830.051.2010273075045.gscs_000500676719.tif
319

  
320

  
321
for f in $fs
322
do
323
year=`echo $f |cut -c 11-14`
324
day=`echo $f |cut -c 15-17 |sed 's/^0*//'`
325
time=`echo $f |cut -c 19-22`
326
month=$(date -d "`date +%Y`-01-01 +$(( ${day} - 1 ))days" +%m)
327
ofile=$month\_$year\_cloud_effective_radius_$f
328
r.in.gdal --quiet -e input=$basedir/$f output=$ofile band=1 title=cloud_effective_radius --overwrite
329
r.mapcalc "$ofile=if($ofile,$ofile,-9999,-9999)"
330
r.null --q map="$ofile" setnull=-9999
331
r.mapcalc "$ofile=$ofile*0.009999999776482582"
332
r.colors --quiet -ne map=$ofile color=precipitation
333
echo Finished $f
334
done
335

  
336
## generate monthly means
337
m02=`g.mlist type=rast pattern="02*"`
338
m02n=`echo $m02 | wc -w`
339

  
340
m02p=`printf '%q+' $m02 | sed 's/\(.*\)./\1/'`
341
r.mapcalc "m02=($m02p)/$m02n"
342

  
343
#  g.mremove -f rast=02*
344

  
345

  
climate/procedures/MOD06_L2_data_compile_netcdf.r
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

  
climate/procedures/MOD06_L2_data_compile_tif2netcdf.r
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
#vars=paste(c("Cloud_Effective_Radius","Cloud_Optical_Thickness","Cloud_Water_Path"))
73

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

  
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
  print(paste("Starting file",basename(file)))
84
  tempfile=paste(tempdir(),"/",sub("hdf$","tif",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_GEOTIFF:",length(vars),sep="")
89
#  hdr=paste("NUM_RUNS = ",length(vars),"|",sep="")
90
  grp=paste("
91
BEGIN
92
INPUT_FILENAME=",file,"
93
OBJECT_NAME=mod06
94
FIELD_NAME=",vars,"|
95
BAND_NUMBER = 1
96
OUTPUT_PIXEL_SIZE_X=1000
97
OUTPUT_PIXEL_SIZE_Y=1000
98
SPATIAL_SUBSET_UL_CORNER = ( ",upleft," )
99
SPATIAL_SUBSET_LR_CORNER = ( ",lowright," )
100
RESAMPLING_TYPE = ",ifelse(grepl("Flag|Mask",vars),"NN","NN"),"
101
OUTPUT_PROJECTION_TYPE = SIN
102
ELLIPSOID_CODE = WGS84
103
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  )
104
OUTPUT_TYPE = GEO
105
#OUTPUT_FILENAME = ",paste(tempfile,paste(vars,".tif",sep=""),sep=""),"
106
OUTPUT_FILENAME = ",tempfile,"
107
END
108

  
109

  
110
",sep="")
111
  ## if any remnants from previous runs remain, delete them
112
  if(length(list.files(tempdir(),pattern=basename(tempfile)))>0)
113
    file.remove(list.files(tempdir(),pattern=basename(tempfile),full=T))
114
  ## write it to a file
115
  cat(c(hdr,grp)    , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
116
  ## now run the swath2grid tool  - must be run as root (argh!)!
117
  ## write the tiff file
118
  log=system(paste("sudo MRTDATADIR=/usr/local/heg/data ",
119
    "PGSHOME=/usr/local/heg/TOOLKIT_MTD PWD=/home/adamw /usr/local/heg/bin/swtif -p ",
120
    paste(tempdir(),"/",basename(file),"_MODparms.txt -d",sep=""),sep=""),intern=T)
121
  ## convert to netcdf to extract metadata
122
  system(paste("NCARG_ROOT=\"/usr/local/ncl_ncarg-6.0.0\" ncl_convert2nc ",
123
               file," -o ",tempdir()," -B ",sep=""))
124
  nc=nc_open(sub("[.]tif$",".nc",tempfile))
125
  
126
  ## read variables one by one into R to expand the file 
127
  for(v in vars){
128
    atts=ncatt_get(nc,v)
129
    outfile=sub("[.]hdf$",paste("_",v,".nc",sep=""),paste(outdir,"/",fs$file[i],sep=""))
130
    QA=grepl("Flag|Mask",v)
131
    td=expand(raster(tempfile,band=which(v==vars)),ge2,value=ifelse(QA,0,-9999))
132
    projection(td)=CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0")
133

  
134
    NAvalue(td)=ifelse(QA,0,-9999)
135
    ## get netcdf attributes
136
    ncfile1=paste(tempdir(),"/",sub("hdf$","nc",basename(file)),sep="")
137
    writeRaster(td,ncfile1,overwrite=T,datatype=ifelse(QA,"INT1U","INT2S"),NAflag=ifelse(QA,0,-9999))
138

  
139
    ## add time variable
140
    print("Adding time dimension")
141
    system(paste("ncecat -O -u time ",ncfile1,outfile))
142
    system(paste("ncap2 -s \'time[time]=",
143
                 as.numeric(difftime(fs$datetime[i],origin,units="mins")),"\'  ",outfile,sep=""))
144

  
145
 
146
######################################################################################
147

  
148
  print("Updating netCDF dimensions")
149
    ## rename dimension variables
150
    ## writeraster incorrectly labels the dimensions!  y=easting!
151
    system(paste("ncrename -d northing,x -d easting,y -v northing,x -v easting,y -v variable,",v," ",outfile,sep=""))
152
    system(paste("ncap2 -s \'lat[x,y]=0;lon[x,y]=0\' ",outfile))
153
    system(paste("ncap2 -s \'sinusoidal=0\' ",outfile))
154
    
155
    ## Get corner coordinates and convert to cell centers
156
    ncd=system(paste("gdalinfo ",tempfile),intern=T)
157
#    UL= as.numeric(strsplit(gsub("[a-z]|[A-Z]|[\\]|[\t]|[\"]|[=]|[(]|[)]|[,]","",ncd[grep("Upper Left",ncd)]),
158
#      " +")[[1]][2:3])+c(500,-500)
159
#    LR= as.numeric(strsplit(gsub("[a-z]|[A-Z]|[\\]|[\t]|[\"]|[=]|[(]|[)]|[,]","",ncd[grep("Lower Right",ncd)]),
160
#      " +")[[1]][2:3])+c(-500,500)
161
    UL=c(extent(td)@xmin,extent(td)@ymax)+c(500,-500)
162
    LR=c(extent(td)@xmax,extent(td)@ymin)+c(-500,500)
163
    xvar=seq(UL[1],LR[1],by=1000)
164
    yvar=seq(UL[2],LR[2],by=-1000)
165
    nc=nc_open(outfile,write=T)
166
    ncvar_put(nc,"x",vals=xvar)
167
    ncvar_put(nc,"y",vals=yvar)
168

  
169
    
170
  ## add lat-lon grid
171
  grid=expand.grid(x=xvar,y=yvar)
172
  coordinates(grid)=c("x","y")
173
  projection(grid)=CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0")
174
  grid2=spTransform(grid,CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
175
  grid=SpatialPointsDataFrame(grid,data=cbind.data.frame(coordinates(grid),coordinates(grid2)))
176
  gridded(grid)=T
177
  fullgrid(grid)=T
178
  colnames(grid@data)=c("x","y","lon","lat")
179

  
180
  xlon=as.matrix(grid["lon"])
181
  ylat=as.matrix(grid["lat"])
182

  
183
  ncvar_put(nc,"lon",vals=xlon)
184
  ncvar_put(nc,"lat",vals=ylat)
185

  
186
  nc_close(nc)
187

  
188
  print("Updating attributes")
189
    system(paste("ncatted -a coordinates,",v,",o,c,\"lat lon\" ",outfile,sep=""))
190
    system(paste("ncatted -a grid_mapping,",v,",o,c,\"sinusoidal\" ",outfile,sep=""))
191
    
192
    system(paste("ncatted -a units,time,o,c,\"Minutes since ",origin,"\" ",outfile))
193
    system(paste("ncatted -a long_name,time,o,c,\"time\"",outfile))
194
    
195
    system(paste("ncatted -a units,y,o,c,\"m\" ",outfile))
196
    system(paste("ncatted -a long_name,y,o,c,\"y coordinate of projection\" ",outfile))
197
    system(paste("ncatted -a standard_name,y,o,c,\"projection_y_coordinate\" ",outfile))
198
    
199
    system(paste("ncatted -a units,x,o,c,\"m\" ",outfile))
200
    system(paste("ncatted -a long_name,x,o,c,\"x coordinate of projection\" ",outfile))
201
    system(paste("ncatted -a standard_name,x,o,c,\"projection_x_coordinate\" ",outfile))
202
    
203
    ## grid attributes
204
    system(paste("ncatted -a units,lat,o,c,\"degrees_north\" ",outfile))
205
    system(paste("ncatted -a long_name,lat,o,c,\"latitude coordinate\" ",outfile))
206
    system(paste("ncatted -a standard_name,lat,o,c,\"latitude\" ",outfile))
207
    
208
    system(paste("ncatted -a units,lon,o,c,\"degrees_east\" ",outfile))
209
    system(paste("ncatted -a long_name,lon,o,c,\"longitude coordinate\" ",outfile))
210
    system(paste("ncatted -a standard_name,lon,o,c,\"longitude\" ",outfile))
211
    
212
    system(paste("ncatted -a grid_mapping_name,sinusoidal,o,c,\"sinusoidal\" ",outfile))
213
    system(paste("ncatted -a standard_parallel,sinusoidal,o,c,\"0\" ",outfile))
214
    system(paste("ncatted -a longitude_of_central_meridian,sinusoidal,o,c,\"0\" ",outfile))
215
    system(paste("ncatted -a latitude_of_central_meridian,sinusoidal,o,c,\"0\" ",outfile))
216

  
217
    
218
    print(paste("Finished ", file))
219
   
220
}
221
    ## clean up and delete temporary files
222
    if(length(list.files(tempdir(),pattern=basename(tempfile)))>0)
223
      file.remove(list.files(tempdir(),pattern=basename(tempfile),full=T))
224

  
225
}
226

  
227

  
228
### update fs with completed files
229
fs$complete=fs$file%in%sub("nc$","hdf",list.files("data/modis/MOD06_L2_nc",pattern="nc$"))
230
table(fs$complete)
231

  
232
#### Run the gridding procedure
233

  
234
#for(fi in which(!fs$complete))
235
#swath2grid(fi,vars=vars,files=fs,outdir=outdir,upleft="47 -125",lowright="40 -115")
236

  
237
system("sudo ls")
238

  
239
mclapply(which(!fs$complete)[1:10],function(fi){
240
  swath2grid(fi,vars=vars,files=fs,
241
             outdir="data/modis/MOD06_L2_test",
242
             upleft="47 -125",lowright="40 -115")},
243
         mc.cores=20)
244

  
245

  
246

  
247
#### Merge the files
248
system(paste("cdo mergetime ",paste(list.files(outdir,full=T),collapse=" "),"data/modis/MOD06L2.nc"))
249

  
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

  
climate/procedures/MOD06_L2_data_summary.r
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(spgrass6)
11
library(rgdal)
12
library(reshape)
13
library(ncdf4)
14
library(geosphere)
15
library(rgeos)
16
library(multicore)
17
library(raster)
18
library(lattice)
19
library(rgl)
20
library(hdf5)
21

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

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

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

  
31

  
32
### Get processed MOD06 nc files
33
datadir="data/modis/MOD06_L2_tif"
34

  
35
fs=data.frame(
36
  path=list.files(datadir,full=T,recursive=T,pattern="tif$"),
37
  file=basename(list.files(datadir,full=F,recursive=T,pattern="tif$")))
38
fs$date=as.Date(substr(fs$file,11,17),"%Y%j")
39
fs$time=substr(fs$file,19,22)
40
fs$datetime=as.POSIXct(strptime(paste(substr(fs$file,11,17),substr(fs$file,19,22)), '%Y%j %H%M'))
41
fs$path=as.character(fs$path)
42
fs$file=as.character(fs$file)
43

  
44

  
45
### get station data
46
load("data/ghcn/roi_ghcn.Rdata")
47
load("data/allstations.Rdata")
48

  
49

  
50
d2=d[d$variable=="ppt"&d$date%in%fs$date,]
51
d2=d2[,-grep("variable",colnames(d2)),]
52
st2=st[st$id%in%d$id,]
53
d2[,c("lon","lat")]=coordinates(st2)[match(d2$id,st2$id),]
54

  
55
## generate list split by day to merge with MOD06 data
56
d2l=split(d2,d2$date)
57

  
58
ds=do.call(rbind.data.frame,mclapply(d2l,function(td){
59
  print(td$date[1])
60
  tfs=fs[fs$date==td$date[1],]
61
  ## make spatial object
62
  tdsp=td
63
  coordinates(tdsp)=c("lon","lat")
64
  projection(tdsp)=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
65
  tdsp=spTransform(tdsp, CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0"))
66

  
67
  td2=do.call(rbind.data.frame,lapply(1:nrow(tfs),function(i){
68
    tnc1=brick(
69
      raster(tfs$path[i],varname="Cloud_Water_Path"),
70
      raster(tfs$path[i],varname="Cloud_Effective_Radius"),
71
      raster(tfs$path[i],varname="Cloud_Optical_Thickness"))
72
    projection(tnc1)=CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0")
73
    td3=as.data.frame(extract(tnc1,tdsp))
74
    if(ncol(td3)==1) return(NULL)
75
    colnames(td3)=
76
      c("Cloud_Water_Path","Cloud_Effective_Radius","Cloud_Optical_Thickness")
77
      ## drop negative values (need to check why these exist)
78
      td3[td3<0]=NA
79
    td3[,c("date","id")]=td[,c("date","id")]
80
      return(td3)
81
    }))
82
      td2=melt(td2,id.vars=c("date","id"))
83
      td2=cast(td2,date+id~variable,fun=mean,na.rm=T)
84
      td2=merge(td,td2)
85
  td2$id=as.character(td2$id)
86
  td2$date=as.character(td2$date)
87
      return(td2)
88
}))
89

  
90
colnames(ds)[grep("value",colnames(ds))]="ppt"
91
ds$ppt=as.numeric(ds$ppt)
92
ds$Cloud_Water_Path=as.numeric(ds$Cloud_Water_Path)
93
ds$Cloud_Effective_Radius=as.numeric(ds$Cloud_Effective_Radius)
94
ds$Cloud_Optical_Thickness=as.numeric(ds$Cloud_Optical_Thickness)
95
ds$date=as.Date(ds$date)
96
ds$year=as.numeric(ds$year)
97
ds$lon=as.numeric(ds$lon)
98
ds$lat=as.numeric(ds$lat)
99
ds=ds[!is.na(ds$ppt),]
100

  
101
save(ds,file="data/modis/pointsummary.Rdata")
102

  
103
load("data/modis/pointsummary.Rdata")
104

  
105

  
106
dsl=melt(ds,id.vars=c("id","date","ppt","lon","lat"),measure.vars=  c("Cloud_Water_Path","Cloud_Effective_Radius","Cloud_Optical_Thickness"))
107

  
108
dsl=dsl[!is.nan(dsl$value),]
109

  
110

  
111
summary(lm(ppt~Cloud_Effective_Radius,data=ds))
112
summary(lm(ppt~Cloud_Water_Path,data=ds))
113
summary(lm(ppt~Cloud_Optical_Thickness,data=ds))
114
summary(lm(ppt~Cloud_Effective_Radius+Cloud_Water_Path+Cloud_Optical_Thickness,data=ds))
115

  
116

  
117
####
118
## mean annual precip
119
dp=d[d$variable=="ppt",]
120
dp$year=format(dp$date,"%Y")
121
dm=tapply(dp$value,list(id=dp$id,year=dp$year),sum,na.rm=T)
122
dms=apply(dm,1,mean,na.rm=T)
123
dms=data.frame(id=names(dms),ppt=dms/10)
124

  
125
dslm=tapply(dsl$value,list(id=dsl$id,variable=dsl$variable),mean,na.rm=T)
126
dslm=data.frame(id=rownames(dslm),dslm)
127

  
128
dms=merge(dms,dslm)
129
dmsl=melt(dms,id.vars=c("id","ppt"))
130

  
131
summary(lm(ppt~Cloud_Effective_Radius,data=dms))
132
summary(lm(ppt~Cloud_Water_Path,data=dms))
133
summary(lm(ppt~Cloud_Optical_Thickness,data=dms))
134
summary(lm(ppt~Cloud_Effective_Radius+Cloud_Water_Path+Cloud_Optical_Thickness,data=dms))
135

  
136

  
137
#### draw some plots
138
#pdf("output/MOD06_summary.pdf",width=11,height=8.5)
139
png("output/MOD06_summary_%d.png",width=1024,height=780)
140

  
141
 ## daily data
142
xyplot(value~ppt/10|variable,data=dsl,
143
       scales=list(relation="free"),type=c("p","r"),
144
       pch=16,cex=.5,layout=c(3,1))
145

  
146

  
147
densityplot(~value|variable,groups=cut(dsl$ppt,c(0,50,100,500)),data=dsl,auto.key=T,
148
            scales=list(relation="free"),plot.points=F)
149

  
150
## annual means
151

  
152
xyplot(value~ppt|variable,data=dmsl,
153
       scales=list(relation="free"),type=c("p","r"),pch=16,cex=0.5,layout=c(3,1),
154
       xlab="Mean Annual Precipitation (mm)",ylab="Mean value")
155

  
156
densityplot(~value|variable,groups=cut(dsl$ppt,c(0,50,100,500)),data=dmsl,auto.key=T,
157
            scales=list(relation="free"),plot.points=F)
158

  
159

  
160
## plot some swaths
161

  
162
nc1=raster(fs$path[3],varname="Cloud_Effective_Radius")
163
nc2=raster(fs$path[4],varname="Cloud_Effective_Radius")
164
nc3=raster(fs$path[5],varname="Cloud_Effective_Radius")
165

  
166
nc1[nc1<=0]=NA
167
nc2[nc2<=0]=NA
168
nc3[nc3<=0]=NA
169

  
170
plot(roi)
171
plot(nc3)
172

  
173
plot(nc1,add=T)
174
plot(nc2,add=T)
175

  
176

  
177
dev.off()
178

  
179

  
climate/procedures/MOD06_L2_data_summary_netcdf.r
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")
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff