Project

General

Profile

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

    
4

    
5
# Redirect all warnings to stderr()
6
#options(warn = -1)
7
#write("2) write() to stderr", stderr())
8
#write("2) write() to stdout", stdout())
9
#warning("2) warning()")
10

    
11

    
12
## import commandline arguments
13
library(getopt)
14
## get options
15
opta <- getopt(matrix(c(
16
                        'date', 'd', 1, 'character',
17
                        'tile', 't', 1, 'character',
18
                        'verbose','v',1,'logical',
19
                        'help', 'h', 0, 'logical'
20
                        ), ncol=4, byrow=TRUE))
21
if ( !is.null(opta$help) )
22
  {
23
       prg <- commandArgs()[1];
24
          cat(paste("Usage: ", prg,  " --date | -d <file> :: The date to process\n", sep=""));
25
          q(status=1);
26
     }
27

    
28

    
29
date=opta$date  #date="20030301"
30
tile=opta$tile #tile="h11v08"
31
verbose=opta$verbose  #print out extensive information for debugging?
32
outdir=paste("daily/",tile,"/",sep="")  #directory for separate daily files
33

    
34
## permanent storage on lou:
35
ldir=paste("lfe1.nas.nasa.gov:/u/awilso10/mod06/daily/",tile,sep="")
36

    
37
print(paste("Processing tile",tile," for date",date))
38

    
39
## load libraries
40
require(reshape)
41
require(geosphere)
42
require(raster)
43
library(rgdal)
44
require(spgrass6)
45
require(RSQLite)
46

    
47

    
48
## specify some working directories
49
setwd("/nobackupp1/awilso10/mod06")
50

    
51
## load ancillary data
52
load(file="allfiles.Rdata")
53

    
54
## load tile information
55
load(file="modlandTiles.Rdata")
56

    
57
## vars to process
58
vars=as.data.frame(matrix(c(
59
  "Cloud_Effective_Radius",              "CER",
60
  "Cloud_Effective_Radius_Uncertainty",  "CERU",
61
  "Cloud_Optical_Thickness",             "COT",
62
  "Cloud_Optical_Thickness_Uncertainty", "COTU",
63
  "Cloud_Water_Path",                    "CWP",
64
  "Cloud_Water_Path_Uncertainty",        "CWPU",
65
  "Cloud_Phase_Optical_Properties",      "CPOP",
66
  "Cloud_Multi_Layer_Flag",              "CMLF",
67
  "Cloud_Mask_1km",                      "CM1",
68
  "Quality_Assurance_1km",               "QA"),
69
  byrow=T,ncol=2,dimnames=list(1:10,c("variable","varid"))),stringsAsFactors=F)
70

    
71

    
72
############################################################################
73
############################################################################
74
### Define functions to process a particular date-tile
75

    
76
#### get swaths
77
#getswaths<-function(tile,db="/nobackupp4/pvotava/DB/export/swath_geo.sql.sqlite3.db"){
78
#  db=dbConnect(
79
#  }
80

    
81
swath2grid=function(file,vars,upleft,lowright){
82
  ## Function to generate hegtool parameter file for multi-band HDF-EOS file
83
  print(paste("Starting file",basename(file)))
84
  outfile=paste(tempdir(),"/",basename(file),sep="")
85
  ## First write the parameter file (careful, heg is very finicky!)
86
  hdr=paste("NUM_RUNS = ",length(vars$varid),"|MULTI_BAND_HDFEOS:",length(vars$varid),sep="")
87
  grp=paste("
88
BEGIN
89
INPUT_FILENAME=",file,"
90
OBJECT_NAME=mod06
91
FIELD_NAME=",vars$variable,"|
92
BAND_NUMBER = 1
93
OUTPUT_PIXEL_SIZE_X=1000
94
OUTPUT_PIXEL_SIZE_Y=1000
95
SPATIAL_SUBSET_UL_CORNER = ( ",upleft," )
96
SPATIAL_SUBSET_LR_CORNER = ( ",lowright," )
97
#RESAMPLING_TYPE =",ifelse(grepl("Flag|Mask|Quality",vars),"NN","CUBIC"),"
98
RESAMPLING_TYPE =NN
99
OUTPUT_PROJECTION_TYPE = SIN
100
OUTPUT_PROJECTION_PARAMETERS = ( 6371007.181 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 )
101
# projection parameters from http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/newPage.cgi?fileName=sn_gctp
102
ELLIPSOID_CODE = WGS84
103
OUTPUT_TYPE = HDFEOS
104
OUTPUT_FILENAME = ",outfile,"
105
END
106

    
107
",sep="")
108

    
109
  ## if any remnants from previous runs remain, delete them
110
  if(length(list.files(tempdir(),pattern=basename(file)))>0)
111
    file.remove(list.files(tempdir(),pattern=basename(file),full=T))
112
  ## write it to a file
113
  cat(c(hdr,grp)    , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
114
  ## now run the swath2grid tool
115
  ## write the gridded file and save the log including the pid of the parent process
116
#  log=system(paste("( /nobackupp1/awilso10/software/heg/bin/swtif -p ",tempdir(),"/",basename(file),"_MODparms.txt -d ; echo $$)",sep=""),intern=T)
117
  log=system(paste("( /nobackupp1/awilso10/software/heg/bin/swtif -p ",tempdir(),"/",basename(file),"_MODparms.txt -d ; echo $$)",sep=""),intern=T,ignore.stderr=T)
118
  ## clean up temporary files in working directory
119
  file.remove(list.files(pattern=
120
              paste("filetable.temp_",
121
              as.numeric(log[length(log)]):(as.numeric(log[length(log)])+3),sep="",collapse="|")))  #Look for files with PID within 3 of parent process
122
  if(verbose) print(log)
123
  print(paste("Finished ", file))
124
}
125

    
126

    
127
##############################################################
128
### Import to GRASS for processing
129

    
130
## function to convert binary to decimal to assist in identifying correct values
131
## this is helpful when defining QA handling below, but isn't used in processing
132
## b2d=function(x) sum(x * 2^(rev(seq_along(x)) - 1)) #http://tolstoy.newcastle.edu.au/R/e2/help/07/02/10596.html
133
## for example:
134
## b2d(c(T,T))
135

    
136
  ## set Grass to overwrite
137
  Sys.setenv(GRASS_OVERWRITE=1)
138
  Sys.setenv(DEBUG=1)
139
  Sys.setenv(GRASS_GUI="txt")
140

    
141
### Function to extract various SDSs from a single gridded HDF file and use QA data to throw out 'bad' observations
142
loadcloud<-function(date,fs,ncfile){
143
  tf=paste(tempdir(),"/grass", Sys.getpid(),"/", sep="")
144
  if(!file.exists(tf))dir.create(tf)
145

    
146
  print(paste("Set up temporary grass session in",tf))
147

    
148
  ## set up temporary grass instance for this PID
149
  initGRASS(gisBase="/u/armichae/pr/grass-6.4.2/",gisDbase=tf,SG=td,override=T,location="mod06",mapset="PERMANENT",home=tf,pid=Sys.getpid())
150
  system(paste("g.proj -c proj4=\"",projection(td),"\"",sep=""),ignore.stdout=T,ignore.stderr=T)
151

    
152
  ## Define region by importing one MOD11A1 raster.
153
  print("Import one MOD11A1 raster to define grid")
154
  execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",gridfile,"\":MODIS_Grid_Daily_1km_LST:Night_view_angl",sep=""),
155
            output="modisgrid",flags=c("quiet","overwrite","o"))
156
  system("g.region rast=modisgrid save=roi --overwrite",ignore.stdout=T,ignore.stderr=T)
157

    
158
  ## Identify which files to process
159
  tfs=fs$file[fs$dateid==date]
160
  ## drop swaths that did not produce an output file (typically due to not overlapping the ROI)
161
  tfs=tfs[tfs%in%list.files(tempdir())]
162
  nfs=length(tfs)
163

    
164
  ## loop through scenes and process QA flags
165
  for(i in 1:nfs){
166
     file=paste(tempdir(),"/",tfs[i],sep="")
167
     ## Cloud Mask
168
     execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Mask_1km_0",sep=""),
169
              output=paste("CM1_",i,sep=""),flags=c("overwrite","o")) ; print("")
170
    ## extract cloudy and 'confidently clear' pixels
171
    system(paste("r.mapcalc <<EOF
172
                CM_cloud_",i," =  ((CM1_",i," / 2^0) % 2) == 1  &&  ((CM1_",i," / 2^1) % 2^2) == 0 
173
                CM_clear_",i," =  ((CM1_",i," / 2^0) % 2) == 1  &&  ((CM1_",i," / 2^1) % 2^2) == 3 
174
EOF",sep=""))
175
    ## QA
176
     execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Quality_Assurance_1km_0",sep=""),
177
             output=paste("QA_",i,sep=""),flags=c("overwrite","o")) ; print("")
178
   ## QA_CER
179
   system(paste("r.mapcalc <<EOF
180
                 QA_COT_",i,"=   ((QA_",i," / 2^0) % 2^1 )==1
181
                 QA_COT2_",i,"=  ((QA_",i," / 2^1) % 2^2 )==3
182
                 QA_COT3_",i,"=  ((QA_",i," / 2^3) % 2^2 )==0
183
                 QA_CER_",i,"=   ((QA_",i," / 2^5) % 2^1 )==1
184
                 QA_CER2_",i,"=  ((QA_",i," / 2^6) % 2^2 )==3
185
EOF",sep="")) 
186
#                 QA_CWP_",i,"=   ((QA_",i," / 2^8) % 2^1 )==1
187
#                 QA_CWP2_",i,"=  ((QA_",i," / 2^9) % 2^2 )==3
188

    
189
   ## Optical Thickness
190
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Optical_Thickness",sep=""),
191
            output=paste("COT_",i,sep=""),
192
            title="cloud_effective_radius",
193
            flags=c("overwrite","o")) ; print("")
194
   execGRASS("r.null",map=paste("COT_",i,sep=""),setnull="-9999")
195
   ## keep only positive COT values where quality is 'useful' and 'very good' & scale to real units
196
   system(paste("r.mapcalc \"COT_",i,"=if(QA_COT_",i,"&&QA_COT2_",i,"&&QA_COT3_",i,"&&COT_",i,">=0,COT_",i,"*0.009999999776482582,null())\"",sep=""))   
197
   ## set COT to 0 in clear-sky pixels
198
   system(paste("r.mapcalc \"COT2_",i,"=if(CM_clear_",i,"==0,COT_",i,",0)\"",sep=""))   
199
   
200
   ## Effective radius ##
201
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Effective_Radius",sep=""),
202
            output=paste("CER_",i,sep=""),
203
            title="cloud_effective_radius",
204
            flags=c("overwrite","o")) ; print("")
205
   execGRASS("r.null",map=paste("CER_",i,sep=""),setnull="-9999")
206
   ## keep only positive CER values where quality is 'useful' and 'very good' & scale to real units
207
   system(paste("r.mapcalc \"CER_",i,"=if(QA_CER_",i,"&&QA_CER2_",i,"&&CER_",i,">=0,CER_",i,"*0.009999999776482582,null())\"",sep=""))   
208
   ## set CER to 0 in clear-sky pixels
209
   system(paste("r.mapcalc \"CER2_",i,"=if(CM_clear_",i,"==0,CER_",i,",0)\"",sep=""))   
210

    
211
   ## Cloud Water Path
212
#   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Water_Path",sep=""),
213
#            output=paste("CWP_",i,sep=""),title="cloud_water_path",
214
#            flags=c("overwrite","o")) ; print("")
215
#   execGRASS("r.null",map=paste("CWP_",i,sep=""),setnull="-9999")
216
   ## keep only positive CER values where quality is 'useful' and 'very good' & scale to real units
217
#   system(paste("r.mapcalc \"CWP_",i,"=if(QA_CWP_",i,"&&QA_CWP2_",i,"&&CWP_",i,">=0,CWP_",i,"*0.009999999776482582,null())\"",sep=""))   
218
   ## set CER to 0 in clear-sky pixels
219
#   system(paste("r.mapcalc \"CWP2_",i,"=if(CM_clear_",i,"==0,CWP_",i,",0)\"",sep=""))   
220
     
221
 } #end loop through sub daily files
222

    
223
#### Now generate daily averages (or maximum in case of cloud flag)
224
  
225
  system(paste("r.mapcalc <<EOF
226
         COT_denom=",paste("!isnull(COT2_",1:nfs,")",sep="",collapse="+"),"
227
         COT_numer=",paste("if(isnull(COT2_",1:nfs,"),0,COT2_",1:nfs,")",sep="",collapse="+"),"
228
         COT_daily=int((COT_numer/COT_denom)*100)
229
         CER_denom=",paste("!isnull(CER2_",1:nfs,")",sep="",collapse="+"),"
230
         CER_numer=",paste("if(isnull(CER2_",1:nfs,"),0,CER2_",1:nfs,")",sep="",collapse="+"),"
231
         CER_daily=int(100*(CER_numer/CER_denom))
232
         CLD_daily=int((max(",paste("if(isnull(CM_cloud_",1:nfs,"),0,CM_cloud_",1:nfs,")",sep="",collapse=","),"))*100) 
233
EOF",sep=""))
234

    
235

    
236
  ### Write the files to a netcdf file
237
  ## create image group to facilitate export as multiband netcdf
238
    execGRASS("i.group",group="mod06",input=c("CER_daily","COT_daily","CLD_daily")) ; print("")
239
   
240
  if(file.exists(ncfile)) file.remove(ncfile)  #if it exists already, delete it
241
  execGRASS("r.out.gdal",input="mod06",output=ncfile,type="Int16",nodata=-32768,flags=c("quiet"),
242
#      createopt=c("FORMAT=NC4","ZLEVEL=5","COMPRESS=DEFLATE","WRITE_GDAL_TAGS=YES","WRITE_LONLAT=NO"),format="netCDF")  #for compressed netcdf
243
      createopt=c("FORMAT=NC","WRITE_GDAL_TAGS=YES","WRITE_LONLAT=NO"),format="netCDF")
244

    
245
  ncopath="/nasa/sles11/nco/4.0.8/gcc/mpt/bin/"
246
  system(paste(ncopath,"ncecat -O -u time ",ncfile," ",ncfile,sep=""))
247
## create temporary nc file with time information to append to MOD06 data
248
  cat(paste("
249
    netcdf time {
250
      dimensions:
251
        time = 1 ;
252
      variables:
253
        int time(time) ;
254
      time:units = \"days since 2000-01-01 00:00:00\" ;
255
      time:calendar = \"gregorian\";
256
      time:long_name = \"time of observation\"; 
257
    data:
258
      time=",as.integer(fs$date[fs$dateid==date][1]-as.Date("2000-01-01")),";
259
    }"),file=paste(tempdir(),"/time.cdl",sep=""))
260
system(paste("ncgen -o ",tempdir(),"/time.nc ",tempdir(),"/time.cdl",sep=""))
261
system(paste(ncopath,"ncks -A ",tempdir(),"/time.nc ",ncfile,sep=""))
262
## add other attributes
263
  system(paste(ncopath,"ncrename -v Band1,CER -v Band2,COT -v Band3,CLD ",ncfile,sep=""))
264
  system(paste(ncopath,"ncatted -a scale_factor,CER,o,d,0.01 -a units,CER,o,c,\"micron\" -a missing_value,CER,o,d,-32768 -a long_name,CER,o,c,\"Cloud Particle Effective Radius\" ",ncfile,sep=""))
265
  system(paste(ncopath,"ncatted -a scale_factor,COT,o,d,0.01 -a units,COT,o,c,\"none\" -a missing_value,COT,o,d,-32768 -a long_name,COT,o,c,\"Cloud Optical Thickness\" ",ncfile,sep=""))
266
  system(paste(ncopath,"ncatted -a scale_factor,CLD,o,d,0.01 -a units,CLD,o,c,\"none\" -a missing_value,CLD,o,d,-32768 -a long_name,CLD,o,c,\"Cloud Mask\" ",ncfile,sep=""))
267
   
268
  
269
### delete the temporary files 
270
  unlink_.gislock()
271
  system("clean_temp")
272
  system(paste("rm -frR ",tf,sep=""))
273
}
274

    
275

    
276
###########################################
277
### Define a wrapper function that will call the two functions above (gridding and QA-handling) for a single tile-date
278

    
279
mod06<-function(date,tile){
280
  print(paste("Processing date ",date," for tile",tile))
281
  #####################################################
282
  ## Run the gridding procedure
283
  tile_bb=tb[tb$tile==tile,] ## identify tile of interest
284
  
285
#  if(venezuela) tile_bb$lat_max=11.0780999176  #increase northern boundary for KT
286

    
287
  lapply(fs$path[fs$dateid==date],swath2grid,vars=vars,upleft=paste(tile_bb$lat_max,tile_bb$lon_min),lowright=paste(tile_bb$lat_min,tile_bb$lon_max))
288

    
289
  ## confirm at least one file for this date is present
290
    outfiles=paste(tempdir(),"/",basename(fs$path[fs$dateid==date]),sep="")
291
    if(!any(file.exists(outfiles))) {
292
      print(paste("########################################   No gridded files for region exist for tile",tile," on date",date))
293
      q("no",status=0)
294
    }
295

    
296
  #####################################################
297
  ## Process the gridded files
298

    
299
  ## run themod06 processing for this date
300
  ncfile=paste(outdir,"/MOD06_",tile,"_",date,".nc",sep="")  #this is the 'final' daily output file
301
  loadcloud(date,fs=fs,ncfile=ncfile)
302

    
303
  ## Confirm that the file has the correct attributes, otherwise delete it
304
  ntime=as.numeric(system(paste("cdo -s ntime ",ncfile),intern=T))
305
  npar=as.numeric(system(paste("cdo -s npar ",ncfile),intern=T))
306
  if(!ntime==1&npar>0) {
307
    print(paste("File for tile ",tile," and date ",date," was not outputted correctly, deleting... "))
308
    file.remove(ncfile)
309
  }
310

    
311
  ## push file to lou and then delete it from pfe
312
#  system(paste("scp ",ncfile," ",ldir,sep="")  )
313
#  file.remove(ncfile)
314
 
315
  ## print out some info
316
  print(paste(" ###################################################################               Finished ",date,"
317
################################################################"))
318
}
319
 
320
## test it
321
##date=notdone[1]
322
mod06(date,tile)
323

    
324
## run it for all dates  - Use this if running on a workstation/server (otherwise use qsub)
325
#mclapply(notdone,mod06,tile,mc.cores=ncores) # use ncores/2 because system() commands can add second process for each spawned R
326
#foreach(i=notdone[1:3],.packages=(.packages())) %dopar% mod06(i,tile)
327
#foreach(i=1:20) %dopar% print(i)
328

    
329
## delete old files
330
#system("cleartemp")
331

    
332
q("no",status=0)
(10-10/15)