Project

General

Profile

« Previous | Next » 

Revision ca0865a8

Added by Adam M. Wilson about 11 years ago

Rearranging files

View differences:

climate/procedures/Build_Global_MODIS_tiles.R
1
### this script generates empty tifs that align with the MODIS land tiles, but are available globally
2
library(raster)
3

  
4
######
5
### proceed by raster using information at http://code.env.duke.edu/projects/mget/wiki/SinusoidalMODIS
6
maketile=function(tile,type="raster",outdir="MODTILES"){
7
  ## check tile
8
  ## list of tile outside valid region
9
  nodata=c('h00v00','h01v00','h02v00','h03v00','h04v00','h05v00','h06v00','h07v00','h08v00','h09v00','h10v00',
10
    'h11v00','h12v00','h13v00','h22v00','h23v00','h24v00','h25v00','h26v00','h27v00','h28v00','h29v00','h30v00','h31v00',
11
    'h32v00','h33v00','h34v00','h35v00','h00v01','h01v01','h02v01','h03v01','h04v01','h05v01','h06v01','h07v01','h08v01',
12
    'h09v01','h10v01','h25v01','h26v01','h27v01','h28v01','h29v01','h30v01','h31v01','h32v01','h33v01','h34v01','h35v01',
13
    'h00v02','h01v02','h02v02','h03v02','h04v02','h05v02','h06v02','h07v02','h08v02','h27v02','h28v02','h29v02',
14
    'h30v02','h31v02','h32v02','h33v02','h34v02','h35v02','h00v03','h01v03','h02v03','h03v03','h04v03','h05v03','h30v03',
15
    'h31v03','h32v03','h33v03','h34v03','h35v03','h00v04','h01v04','h02v04','h03v04','h32v04','h33v04','h34v04','h35v04',
16
    'h00v05','h01v05','h34v05','h35v05','h00v06','h35v06','h00v11','h35v11','h00v12','h01v12','h34v12','h35v12','h00v13',
17
    'h01v13','h02v13','h03v13','h32v13','h33v13','h34v13','h35v13','h00v14','h01v14','h02v14','h03v14','h04v14','h05v14',
18
    'h30v14','h31v14','h32v14','h33v14','h34v14','h35v14','h00v15','h01v15','h02v15','h03v15','h04v15','h05v15','h06v15',
19
    'h07v15','h08v15','h27v15','h28v15','h29v15','h30v15','h31v15','h32v15','h33v15','h34v15','h35v15','h00v16','h01v16',
20
    'h02v16','h03v16','h04v16','h05v16','h06v16','h07v16','h08v16','h09v16','h10v16','h25v16','h26v16','h27v16','h28v16',
21
    'h29v16','h30v16','h31v16','h32v16','h33v16','h34v16','h35v16','h00v17','h01v17','h02v17','h03v17','h04v17','h05v17',
22
    'h06v17','h07v17','h08v17','h09v17','h10v17','h11v17','h12v17','h13v17','h22v17','h23v17','h24v17','h25v17','h26v17',
23
    'h27v17','h28v17','h29v17','h30v17','h31v17','h32v17','h33v17','h34v17','h35v17') 
24
  if(tile%in%nodata) {print(paste(tile," not in region with data, skipping"));return(NULL)}
25
  ##
26
  h=as.numeric(substr(tile,2,3))
27
  v=as.numeric(substr(tile,5,6))
28
  ## Earth Width (m)
29
  ew=20015109.354*2
30
  ## Tile width or height = earth width / 36 = (20015109.354 + 20015109.354) / 36 = 1111950.5196666666 m
31
  tw=ew/36
32
  ## number of cells (1200 for 1km data)
33
  nc=1200
34
  ##1 km Cell size = tile width / cells
35
  cs=tw/nc
36
  ##X coordinate of tile lower-left corner = -20015109.354 + horizontal tile number * tile width
37
  llx= -(ew/2) + (h * tw)
38
  lly= -(ew/4) + ((17-v) * tw)
39
  ## projection
40
  proj="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs" 
41
  ## make extent
42
  ext=extent(llx,llx+(nc*cs),lly,lly+(nc*cs))
43
  grid=raster(ext,nrows=nc,ncol=nc,crs=proj)
44
  names(grid)=tile
45
  if(type=="raster") {
46
    writeRaster(grid,paste(outdir,"/",tile,".tif",sep=""),options=c("COMPRESS=LZW"),datatype="INT1U",overwrite=T)
47
    return(grid)
48
  }
49
  if(type=="extent") {
50
    grid2=data.frame(tile=tile,t(as.vector(extent(grid))))
51
    names(grid2)=c("tile","xmin", "xmax", "ymin", "ymax")
52
  return(grid2)
53
}
54
}
55

  
56
## run it and save the extents as an Rdata object for easy retrieval
57
gs=expand.grid(h=0:35,v=0:17)
58
gs$tile=paste("h",sprintf("%02d",gs$h),"v",sprintf("%02d",gs$v),sep="")
59
modtiles=lapply(1:nrow(gs),function(i) maketile(gs$tile[i]))
60
names(modtiles)=gs$tile
61

  
62
## function to confirm that this method results in identical (e same extent, number of rows and columns, projection, resolution, and origin) rasters as MODIS LST data
63
checkgrid<-function(tile){
64
  print(tile)
65
  ## path to MOD11A1 file for this tile to align grid/extent
66
  gridfile=list.files("/nobackupp4/datapool/modis/MOD11A2.005/2009.01.01",pattern=paste(tile,".*[.]hdf$",sep=""),recursive=T,full=T)[1]
67
  if(!file.exists(gridfile)) return(NULL)
68
  td=raster(paste("HDF4_EOS:EOS_GRID:\"",gridfile,"\":MODIS_Grid_8Day_1km_LST:LST_Day_1km",sep=""))
69
  td2=maketile(tile)
70
  return(compareRaster(td,td2,res=T,orig=T,rotation=T))
71
}
72

  
73
testing=F
74
if(testing){
75
  ## make the comparison for every tile
76
  dat=do.call(c,lapply(gs$tile,checkgrid))
77
  ## summarize the results
78
  table(dat)
79
}
80

  
81
### make table of extents
82
modtiles=do.call(rbind,lapply(1:nrow(gs),function(i) maketile(gs$tile[i],type="extent")))
83

  
84
## get list of tiles with some land
85
land=read.table("http://modis-land.gsfc.nasa.gov/pdf/sn_bound_10deg.txt",skip=6,nrows=648,header=T)
86
land$tile=paste("h",sprintf("%02d",land$ih),"v",sprintf("%02d",land$iv),sep="")
87
land=land[land$lon_min!=-999,]
88
modtiles$land=modtiles$tile%in%land$tile
89

  
90

  
91
## write the table as text
92
write.csv(modtiles,"MODIS_Tiles.csv",row.names=F,quote=F)
climate/procedures/EE_simple.py
1
import ee
2
from ee import mapclient
3

  
4
import logging
5
logging.basicConfig()
6

  
7
MY_SERVICE_ACCOUNT = '511722844190@developer.gserviceaccount.com'  # replace with your service account
8
MY_PRIVATE_KEY_FILE = '/Users/adamw/EarthEngine-privatekey.p12'       # replace with you private key file path
9

  
10
ee.Initialize(ee.ServiceAccountCredentials(MY_SERVICE_ACCOUNT, MY_PRIVATE_KEY_FILE))
11

  
12

  
13

  
14
image = ee.Image('srtm90_v4')
15
map = ee.mapclient.MapClient()
16
map.addOverlay(mapclient.MakeOverlay(image.getMapId({'min': 0, 'max': 3000})))
climate/procedures/GHCND_stations_extraction_study_area.R
1
##################    Data preparation for interpolation   #######################################
2
############################ Extraction of station data ##########################################
3
#This script perform queries on the Postgres database ghcn for stations matching the             #
4
#interpolation area. It requires the following inputs:                                           #
5
# 1)the text file ofGHCND  stations from NCDC matching the database version release              #
6
# 2)a shape file of the study area with geographic coordinates: lonlat WGS84                     #                                                     #       
7
# 3)a new coordinate system can be provided as an argument                                       #
8
# 4)the variable of interest: "TMAX","TMIN" or "PRCP"                                            #
9
#                                                                                                #
10
#The outputs are text files and a shape file of a time subset of the database                    #
11
#AUTHOR: Benoit Parmentier                                                                       #
12
#DATE: 06/02/212                                                                                 #
13
#PROJECT: NCEAS INPLANT: Environment and Organisms --TASK#363--                                  #
14
##################################################################################################
15

  
16
###Loading R library and packages   
17
library(RPostgreSQL)
18
library(sp)                                             # Spatial pacakge with class definition by Bivand et al.
19
library(spdep)                                          # Spatial pacakge with methods and spatial stat. by Bivand et al.
20
library(rgdal)                                          # GDAL wrapper for R, spatial utilities
21
library(rgeos)                                          # Polygon buffering and other vector operations
22
library(reshape)
23
library(raster)
24

  
25
### Parameters and arguments
26

  
27
db.name <- "ghcn"                #name of the Postgres database
28
var <- "PRCP"                    #name of the variables to keep: TMIN, TMAX or PRCP
29
year_start<-"1970"               #starting year for the query (included)
30
year_end<-"2011"                 #end year for the query (excluded)
31
buffer=500                      #  size of buffer around shapefile to include in spatial query (in km), set to 0 to use no buffer
32
infile2<-"ghcnd-stations.txt"                             #This is the textfile of station locations from GHCND
33
new_proj<-"+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs"
34
#tile="h11v08" 
35
tile="h09v04"
36
tile="h21v09"
37

  
38
#out_prefix<-"20121212"                                                 #User defined output prefix
39

  
40
#for Adam
41
outpath="/home/wilson/data"
42
path="/home/wilson/data"
43
setwd(path) 
44

  
45

  
46
############ START OF THE SCRIPT #################
47

  
48
#####  Connect to Station database
49
drv <- dbDriver("PostgreSQL")
50
db <- dbConnect(drv, dbname=db.name)#,options="statement_timeout = 1m")
51

  
52
##### STEP 1: Select station in the study area
53
## get MODLAND tile information
54
#tb=read.table("http://landweb.nascom.nasa.gov/developers/sn_tiles/sn_bound_10deg.txt",skip=6,nrows=648,header=T)
55
#tb$tile=paste("h",sprintf("%02d",tb$ih),"v",sprintf("%02d",tb$iv),sep="")
56
#tile_bb=tb[tb$tile==tile,] ## identify tile of interest
57
#roi_ll=extent(tile_bb$lon_min,tile_bb$lon_max,tile_bb$lat_min,tile_bb$lat_max)
58

  
59
modgrid=readOGR("/home/wilson/data/modisgrid","modis_sinusoidal_grid_world")
60
roi=modgrid[modgrid$h==as.numeric(substr(tile,2,3))&modgrid$v==as.numeric(substr(tile,5,6)),]
61
CRS_interp="+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
62
interp_area=spTransform(roi,CRS(CRS_interp))
63

  
64
#####  Buffer shapefile if desired
65
##     This is done to include stations from outside the region in the interpolation fitting process and reduce edge effects when stiching regions
66
if(buffer>0){  #only apply buffer if buffer >0
67
  interp_area=gUnionCascaded(interp_area)  #dissolve any subparts of roi (if there are islands, lakes, etc.)
68
  interp_areaC=gCentroid(interp_area)       # get centroid of region
69
  interp_areaB=spTransform(                # buffer roi (transform to azimuthal equidistant with centroid of region for most (?) accurate buffering, add buffer, then transform to WGS84)
70
    gBuffer(
71
      spTransform(interp_area,
72
                  CRS(paste("+proj=aeqd +lat_0=",interp_areaC@coords[2]," +lon_0=",interp_areaC@coords[1]," +ellps=WGS84 +datum=WGS84 +units=m +no_defs ",sep=""))),
73
      width=buffer*1000),                  # convert buffer (km) to meters
74
    CRS(CRS_interp))                       # reproject back to original projection
75
  interp_area=interp_areaB                 # replace original region with buffered region
76
}
77

  
78
## get bounding box of study area
79
bbox=bbox(interp_area)
80

  
81
### read in station location information from database
82
### use the bbox of the region to include only station in rectangular region to speed up overlay
83
dat_stat=dbGetQuery(db, paste("SELECT id,name,latitude,longitude
84
                  FROM stations
85
                  WHERE latitude>=",bbox[2,1]," AND latitude<=",bbox[2,2],"
86
                  AND longitude>=",bbox[1,1]," AND longitude<=",bbox[1,2],"
87
                  ;",sep=""))
88
coordinates(dat_stat)<-c("longitude","latitude")
89
proj4string(dat_stat)<-CRS_interp
90

  
91

  
92
# Spatial query to find relevant stations
93
inside <- !is.na(over(dat_stat, as(interp_area, "SpatialPolygons")))  #Finding stations contained in the current interpolation area
94
stat_roi<-dat_stat[inside,]                                            #Finding stations contained in the current interpolation area
95
stat_roi<-spTransform(stat_roi,CRS(new_proj))         # Project from WGS84 to new coord. system
96

  
97
#Quick visualization of station locations
98
#plot(interp_area, axes =TRUE)
99
#plot(stat_roi, pch=1, col="red", cex= 0.7, add=TRUE)
100
#legend("topleft", pch=1,col="red",bty="n",title= "Stations",cex=1.6)
101

  
102
#### STEP 2: Connecting to the database and query for relevant data 
103

  
104
##  Query to link station location information and observations
105
##  Concatenate date columns into single field for easy convert to date
106
##  Divide value by 10 to convert to degrees C and mm
107
##  Subset to years in year_start -> year_end
108
##  Drop missing values (-9999)
109
##  Drop observations that failed quality control (keep only qflag==NA)
110
system.time(
111
  dd<<-dbGetQuery(db,  #save object dd (data daily)
112
                          paste("SELECT station,year||'-'||month||'-'||day AS date,value / 10.0 as value,latitude,longitude,elevation
113
                                 FROM ghcn, stations
114
                                 WHERE station = id
115
                                 AND id IN ('",paste(stat_roi$id,collapse="','"),"')
116
                                 AND element='",var,"'
117
                                 AND year>=",year_start,"
118
                                 AND year<",year_end,"
119
                                 AND value<>-9999
120
                                 AND qflag IS NULL
121
                                 ;",sep=""))
122
  )  ### print used time in seconds  - only taking ~30 seconds....
123

  
124
dd=dd[!is.na(dd$value),]  #drop any NA values
125

  
126
#################################################################
127
### STEP 3: generate monthly means for climate-aided interpolation
128

  
129
### first extract average daily values by year.  
130
system.time(
131
           dm<<-dbGetQuery(db,  # create dm object (data monthly)
132
                          paste("SELECT station,month,count(value) as count,avg(value)/10.0 as value,latitude,longitude,elevation
133
                                 FROM ghcn, stations
134
                                 WHERE station = id
135
                                 AND id IN ('",paste(stat_roi$id,collapse="','"),"')
136
                                 AND element='",var,"'
137
                                 AND year>=",year_start,"
138
                                 AND year<",year_end,"
139
                                 AND value<>-9999
140
                                 AND qflag IS NULL
141
                                 GROUP BY station, month,latitude,longitude,elevation
142
                                 ;",sep=""))
143
            )  ### print used time in seconds  - only taking ~30 seconds....
144

  
145
### drop months with fewer than 75% of the data observations
146
### is 75% the right number?
147
#dm=dm[dm$count>=(.75*10*30),]
148

  
149
## add the monthly data to the daily table
150
dd$month=as.numeric(as.character(format(as.Date(dd$date),"%m")))
151
dd$avgvalue=dm$value[match(paste(dd$station,dd$month),paste(dm$station,dm$month))]
152
dd$avgcount=dm$count[match(paste(dd$station,dd$month),paste(dm$station,dm$month))]
153

  
154
### Generate log-transformed ratio of daily:monthly ppt and add it to daily data
155
if(var=="PRCP"){
156
  dd$anom=log((1+dd$value)/(1+dd$avgvalue))
157
  dd$anom[dd$anom==Inf|dd$anom2==-Inf]=NA
158
}
159

  
160
### Generate temperature anomolies for each daily value
161
if(var!="PRCP"){
162
  dd$anom=dd$value-dd$avgvalue
163
}
164

  
165

  
166
###  Transform the subset data frame in a spatial data frame and reproject
167
dd_sp<-SpatialPointsDataFrame (dd[,c('longitude','latitude')],data=dd,proj=CRS(CRS_interp)) 
168
dd_sp<-spTransform(dd_sp,CRS(new_proj))         # Project from WGS84 to new coord. system
169

  
170
###  Transform the subset data frame in a spatial data frame and reproject
171
dm_sp<-SpatialPointsDataFrame (dm[,c('longitude','latitude')],data=dm,proj=CRS(CRS_interp)) 
172
dm_sp<-spTransform(dm_sp,CRS(new_proj))         # Project from WGS84 to new coord. system
173

  
174
################################################################
175
### STEP 4: Save results and outuput in textfile and a shape file
176

  
177
##  Save shapefile of station locations
178
writeOGR(stat_roi,outpath,paste("station_location_",tile,"_",var,sep=""),driver ="ESRI Shapefile")
179

  
180
## save shapefile of daily observations
181
writeOGR(dd_sp,outpath,paste("/station_daily_",tile,"_",var,sep=""), driver ="ESRI Shapefile") #Note that the layer name is the file name without extension
182

  
183
### write monthly data
184
writeOGR(dm_sp, outpath, paste("/station_monthly_",tile,"_",var,sep=""), driver ="ESRI Shapefile") #Note that the layer name is the file name without extension
185

  
186
##### END OF SCRIPT ##########
climate/procedures/GetCloudProducts.R
1
## download cloud products from GEWEX for comparison
2
setwd("~/acrobates/adamw/projects/cloud/")
3
library(rasterVis)
4

  
5

  
6
## get PATMOS-X 1-deg data
7
dir1="data/gewex/"
8

  
9
for(y in 2000:2009) system(paste("wget -nc -P ",dir1," http://climserv.ipsl.polytechnique.fr/gewexca/DATA/instruments/PATMOSX/variables/CA/CA_PATMOSX_NOAA_0130PM_",y,".nc.gz",sep=""))
10
## decompress
11
lapply(list.files(dir1,pattern="gz",full=T),function(f) system(paste("gzip -dc < ",f," > ",dir1," ",sub(".gz","",basename(f)),sep="")))
12
## mergetime
13
system(paste("cdo -mergetime ",list.files(dir1,pattern="nc$",full=T)," ",dir1,"CA_PATMOSX_NOAA.nc",sep=""))
14

  
15

  
16
## Get 
17

  
climate/procedures/HelloRmpi.r
1
# Echo out library paths
2
.libPaths()
3

  
4
# Load the R MPI package if it is not already loaded
5
if (!is.loaded("mpi_initialize")) {
6
  library("Rmpi")
7
}
8

  
9
# Echo out libraries loaded
10
library()
11

  
12
# Echo out what is loaded
13
search()
14

  
15
# Spawn as many slaves as possible
16
mpi.spawn.Rslaves()
17

  
18
# In case R exits unexpectedly, have it automatically clean up
19
# resources taken up by Rmpi (slaves, memory, etc...)
20
.Last <- function(){
21
  if (is.loaded("mpi_initialize")){
22
            if (mpi.comm.size(1) > 0){
23
                              print("Please use mpi.close.Rslaves() to close slaves.")
24
                                              mpi.close.Rslaves()
25
                            }
26
                    print("Please use mpi.quit() to quit R")
27
                    .Call("mpi_finalize")
28
          }
29
}
30

  
31
# Tell all slaves to return a message identifying themselves
32
mpi.remote.exec(paste("I am",mpi.comm.rank(),"of",mpi.comm.size()))
33

  
34
# Tell all slaves to close down, and exit the program
35
mpi.close.Rslaves()
36
mpi.quit()
climate/procedures/HelloRmpi.r.Rout
1

  
2
R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows"
3
Copyright (C) 2012 The R Foundation for Statistical Computing
4
ISBN 3-900051-07-0
5
Platform: x86_64-unknown-linux-gnu (64-bit)
6

  
7
R is free software and comes with ABSOLUTELY NO WARRANTY.
8
You are welcome to redistribute it under certain conditions.
9
Type 'license()' or 'licence()' for distribution details.
10

  
11
R is a collaborative project with many contributors.
12
Type 'contributors()' for more information and
13
'citation()' on how to cite R or R packages in publications.
14

  
15
Type 'demo()' for some demos, 'help()' for on-line help, or
16
'help.start()' for an HTML browser interface to help.
17
Type 'q()' to quit R.
18

  
19
> # Echo out library paths
20
> .libPaths()
21
[1] "/home1/awilso10/R/x86_64-unknown-linux-gnu-library/2.15"
22
[2] "/nasa/R/2.15.1/lib64/R/library"                         
23
> 
24
> # Load the R MPI package if it is not already loaded
25
> if (!is.loaded("mpi_initialize")) {
26
+   library("Rmpi")
27
+ }
climate/procedures/MOD06_Climatology.r
1
### Process a folder of daily MOD06 HDF files to produce a climatology
2

  
3
## import commandline arguments
4
library(getopt)
5
## get options
6
opta <- getopt(matrix(c(
7
                        'tile', 't', 1, 'character',
8
                        'verbose','v',1,'logical'
9
                        ), ncol=4, byrow=TRUE))
10

  
11
tile=opta$tile #tile="h11v08"
12
verbose=opta$verbose  #print out extensive information for debugging?
13

  
14
### directory containing daily files
15
outdir=paste("daily/",tile,"/",sep="")  #directory for separate daily files
16

  
17
### directory to hold climatology
18
outdir2="summary" #directory for combined daily files and summarized files
19
if(!file.exists(outdir2)) dir.create(outdir2)
20

  
21
### path to NCO
22
ncopath="/nasa/sles11/nco/4.0.8/gcc/mpt/bin/"
23

  
24
### Vector of variables that must be in file or they will be deleted.
25
###  Formated as output from system(paste("cdo -s showvar ",fdly$path[i]),intern=T)
26
finalvars=" CER COT CLD"
27

  
28

  
29
################################################################################
30
## Get list of all daily files
31
if(verbose) print("Checking daily output in preparation for generating climatology")
32

  
33
 fdly=data.frame(path=list.files(outdir,pattern="nc$",full=T),stringsAsFactors=F)
34
  fdly$file=basename(fdly$path)
35
  fdly$dateid=substr(fdly$file,14,21)
36
  fdly$date=as.Date(substr(fdly$file,14,21),"%Y%m%d")
37
  fdly$month=format(fdly$date,"%m")
38
  fdly$year=format(fdly$date,"%Y")
39
nrow(fdly)
40

  
41
## check validity (via npar and ntime) of nc files
42
#for(i in 1:nrow(fdly)){
43
#  fdly$ntime[i]<-as.numeric(system(paste("cdo -s ntime ",fdly$path[i]),intern=T))
44
#  fdly$npar[i]<-as.numeric(system(paste("cdo -s npar ",fdly$path[i]),intern=T))
45
#  fdly$fyear[i]<-as.numeric(system(paste("cdo -s showyear ",fdly$path[i]),intern=T))
46
#  fdly$fmonth[i]<-as.numeric(system(paste("cdo -s showmon ",fdly$path[i]),intern=T))
47
#  fdly$fvar[i]<-system(paste("cdo -s showvar ",fdly$path[i]),intern=T)
48
#  print(paste(i," out of ",nrow(fdly)," for year ",  fdly$fyear[i]))
49
#}
50

  
51
## print some summaries
52
if(verbose) print("Summary of available daily files")
53
print(table(fdly$year))
54
print(table(fdly$month))
55
#print(table(fdly$fvar))
56

  
57
## Identify which files failed test
58
#fdly$drop=is.na(fdly$npar)|fdly$fvar!=finalvars
59

  
60
## delete files that fail check?
61
delete=F
62
if(delete) {
63
  print(paste(sum(fdly$drop),"files will be deleted"))
64
  file.remove(as.character(fdly$path[fdly$drop]))
65
}
66
## remove dropped files from list
67
#fdly=fdly[!fdly$drop,]
68

  
69
#################################################################################
70
## Combine the year-by-year files into a single daily file in the summary directory (for archiving)
71
if(verbose) print("Merging daily files into single file output")
72

  
73
## create temporary directory to put intermediate files (will be deleted when R quits)
74
tsdir=paste(tempdir(),"/summary",sep="")
75
if(!file.exists(tsdir)) dir.create(tsdir,recursive=T)
76

  
77
## merge all daily files to create a single file with all dates
78
system(paste(ncopath,"ncrcat -O ",outdir,"/*nc ",outdir2,"/MOD06_",tile,"_daily.nc",sep=""))
79

  
80
## Update attributes
81
system(paste(ncopath,"ncatted ",
82
" -a units,time,o,c,\"days since 2000-1-1 0:0:0\" ",
83
" -a title,global,o,c,\"MODIS Cloud Product (MOD06) Daily Timeseries\" ",
84
" -a institution,global,o,c,\"Yale University\" ",
85
" -a source,global,o,c,\"MODIS Cloud Product (MOD06)\" ",
86
" -a comment,global,o,c,\"Compiled by Adam M. Wilson (adam.wilson@yale.edu)\" ",
87
outdir2,"/MOD06_",tile,"_daily.nc",sep=""))
88

  
89
### produce a monthly timeseries?
90
#system(paste("cdo -O monmean ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_monmean.nc",sep=""))
91

  
92
#############################
93
##  Generate the Climatologies
94
if(verbose) print("Generate monthly climatologies")
95

  
96
myear=as.integer(max(fdly$year))  #this year will be used in all dates of monthly climatologies (and day will = 15)
97

  
98
## Monthly means
99
if(verbose) print("Calculating the monthly means")
100
system(paste("cdo -O sorttimestamp -setyear,",myear," -setday,15 -ymonmean ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymonmean.nc",sep=""),wait=T)
101

  
102
## Monthly standard deviation
103
if(verbose) print("Calculating the monthly SD")
104
system(paste("cdo -O sorttimestamp -setyear,",myear," -setday,15 -ymonstd ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymonstd.nc",sep=""))
105
system(paste(ncopath,"ncrename -v CER,CER_sd -v CLD,CLD_sd -v COT,COT_sd ",tsdir,"/MOD06_",tile,"_ymonstd.nc",sep=""))
106
system(paste(ncopath,"ncatted ",
107
" -a long_name,CER_sd,o,c,\"Cloud Particle Effective Radius (standard deviation of daily observations)\" ",
108
" -a long_name,CLD_sd,o,c,\"Cloud Mask (standard deviation of daily observations)\" ",
109
" -a long_name,COT_sd,o,c,\"Cloud Optical Thickness (standard deviation of daily observations)\" ",
110
tsdir,"/MOD06_",tile,"_ymonstd.nc",sep=""))
111

  
112
## cer > 20
113
if(verbose) print("Calculating the proportion of days with CER > 20")
114
system(paste("cdo -O  sorttimestamp -setyear,",myear," -setday,15 -ymonmean -gtc,20 -selvar,CER ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymoncer20.nc",sep=""))
115
system(paste(ncopath,"ncrename -v CER,CER20 ",tsdir,"/MOD06_",tile,"_ymoncer20.nc",sep=""))
116
system(paste(ncopath,"ncatted ",
117
" -a long_name,CER20,o,c,\"Proportion of Days with Cloud Particle Effective Radius > 20um\" ",
118
" -a units,CER20,o,c,\"Proportion\" ",
119
tsdir,"/MOD06_",tile,"_ymoncer20.nc",sep=""))
120

  
121
## cld == 0
122
if(verbose) print("Calculating the proportion of cloudy days")
123
system(paste("cdo -O  sorttimestamp -setyear,",myear," -setday,15 -nint -mulc,100 -ymonmean -eqc,0 -setctomiss,1 -selvar,CLD2 ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymoncld0.nc",sep=""))
124
system(paste(ncopath,"ncrename -v CLD2,CLD0 ",tsdir,"/MOD06_",tile,"_ymoncld0.nc",sep=""))
125
system(paste(ncopath,"ncatted ",
126
" -a long_name,CLD0,o,c,\"Proportion of Days with Cloud Mask == 0\" ",
127
" -a units,CLD0,o,c,\"Proportion\" ",
128
tsdir,"/MOD06_",tile,"_ymoncld0.nc",sep=""))
129

  
130
## cld == 0|1
131
if(verbose) print("Calculating the proportion of cloudy days")
132
system(paste("cdo -O  sorttimestamp -setyear,",myear," -setday,15 -nint -mulc,100 -ymonmean -lec,1 -selvar,CLD2 ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymoncld01.nc",sep=""))
133
system(paste(ncopath,"ncrename -v CLD2,CLD01 ",tsdir,"/MOD06_",tile,"_ymoncld01.nc",sep=""))
134
system(paste(ncopath,"ncatted ",
135
" -a long_name,CLD01,o,c,\"Proportion of Days with Cloud Mask == 0|1\" ",
136
" -a units,CLD01,o,c,\"Proportion\" ",
137
tsdir,"/MOD06_",tile,"_ymoncld01.nc",sep=""))
138

  
139
## cld == 1
140
if(verbose) print("Calculating the proportion of uncertain days")
141
system(paste("cdo -O  sorttimestamp -setyear,",myear," -setday,15 -nint -mulc,100 -ymonmean -eqc,1 -selvar,CLD2 ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymoncld1.nc",sep=""))
142
system(paste(ncopath,"ncrename -v CLD2,CLD1 ",tsdir,"/MOD06_",tile,"_ymoncld1.nc",sep=""))
143
system(paste(ncopath,"ncatted ",
144
" -a long_name,CLD1,o,c,\"Proportion of Days with Cloud Mask == 1 (uncertain)\" ",
145
" -a units,CLD1,o,c,\"Proportion\" ",
146
tsdir,"/MOD06_",tile,"_ymoncld1.nc",sep=""))
147

  
148

  
149
## cld >= 2 (setting cld==01 to missing because 'uncertain')
150
if(verbose) print("Calculating the proportion of clear days")
151
system(paste("cdo -O  sorttimestamp -setyear,",myear," -setday,15 -nint -mulc,100 -ymonmean -gtc,1 -setctomiss,1 -selvar,CLD2 ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymoncld2.nc",sep=""))
152
system(paste(ncopath,"ncrename -v CLD2,CLD23 ",tsdir,"/MOD06_",tile,"_ymoncld2.nc",sep=""))
153
system(paste(ncopath,"ncatted ",
154
" -a long_name,CLD23,o,c,\"Proportion of Days with Cloud Mask >= 2 (Probably Clear or Certainly Clear)\" ",
155
" -a units,CLD23,o,c,\"Proportion\" ",
156
tsdir,"/MOD06_",tile,"_ymoncld2.nc",sep=""))
157

  
158
## cld >= 1
159
if(verbose) print("Calculating the proportion of clear days")
160
system(paste("cdo -O  sorttimestamp -setyear,",myear," -setday,15 -nint -mulc,100 -ymonmean -gec,1 -selvar,CLD2 ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymoncld13.nc",sep=""))
161
system(paste(ncopath,"ncrename -v CLD2,CLD13 ",tsdir,"/MOD06_",tile,"_ymoncld13.nc",sep=""))
162
system(paste(ncopath,"ncatted ",
163
" -a long_name,CLD13,o,c,\"Proportion of Days with Cloud Mask >= 1\" ",
164
" -a units,CLD13,o,c,\"Proportion\" ",
165
tsdir,"/MOD06_",tile,"_ymoncld13.nc",sep=""))
166

  
167
## number of observations
168
if(verbose) print("Calculating the number of missing variables")
169
system(paste("cdo -O sorttimestamp  -setyear,",myear," -setday,15 -nint -mulc,100 -ymonmean -eqc,9999 -setmisstoc,9999   -selvar,CER,CLD ",outdir2,"/MOD06_",tile,"_daily.nc ",tsdir,"/MOD06_",tile,"_ymonmiss.nc",sep=""))
170
system(paste(ncopath,"ncrename -v CER,CER_pmiss -v CLD,CLD_pmiss ",tsdir,"/MOD06_",tile,"_ymonmiss.nc",sep=""))
171
system(paste(ncopath,"ncatted ",
172
" -a long_name,CER_pmiss,o,c,\"Proportion of Days with missing data for CER\" ",
173
" -a long_name,CLD_pmiss,o,c,\"Proportion of Days with missing data for CLD\" ",
174
" -a scale_factor,CER_pmiss,o,d,0.01 ",
175
" -a units,CER_pmiss,o,c,\"Proportion\" ",
176
" -a scale_factor,CLD_pmiss,o,d,0.01 ",
177
" -a units,CLD_pmiss,o,c,\"Proportion\" ",
178
tsdir,"/MOD06_",tile,"_ymonmiss.nc",sep=""))
179

  
180
## append variables to a single file
181
if(verbose) print("Append all monthly climatologies into a single file")
182
system(paste(ncopath,"ncks -O ",tsdir,"/MOD06_",tile,"_ymonmean.nc  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
183
system(paste(ncopath,"ncks -A ",tsdir,"/MOD06_",tile,"_ymonstd.nc  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
184
system(paste(ncopath,"ncks -A ",tsdir,"/MOD06_",tile,"_ymoncer20.nc  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
185
system(paste(ncopath,"ncks -A ",tsdir,"/MOD06_",tile,"_ymoncld0.nc  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
186
system(paste(ncopath,"ncks -A ",tsdir,"/MOD06_",tile,"_ymoncld1.nc  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
187
system(paste(ncopath,"ncks -A ",tsdir,"/MOD06_",tile,"_ymoncld2.nc  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
188
system(paste(ncopath,"ncks -A ",tsdir,"/MOD06_",tile,"_ymonmiss.nc  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
189

  
190
## append sinusoidal grid from one of input files as CDO doesn't transfer all attributes
191
if(verbose) print("Clean up file (update attributes, flip latitudes, add grid description")
192

  
193
#system(paste(ncopath,"ncea -d time,0,1 -v sinusoidal ",list.files(outdir,full=T,pattern="[.]nc$")[1],"  ",tsdir,"/sinusoidal.nc",sep=""))
194
#system(paste(ncopath,"ncks -A -d time,0,1 -v sinusoidal ",list.files(outdir,full=T,pattern="[.]nc$")[1],"  ",tsdir,"/MOD06_",tile,"_ymon.nc",sep=""))
195

  
196
## invert latitude so it plays nicely with gdal
197
system(paste(ncopath,"ncpdq -O -a -y ",tsdir,"/MOD06_",tile,"_ymon.nc ",outdir2,"/MOD06_",tile,".nc",sep=""))
198

  
199
## update attributes
200
system(paste(ncopath,"ncatted ",
201
#" -a standard_parallel,sinusoidal,o,c,\"0\" ",
202
#" -a longitude_of_central_meridian,sinusoidal,o,c,\"0\" ",
203
#" -a latitude_of_central_meridian,sinusoidal,o,c,\"0\" ",
204
" -a units,time,o,c,\"days since 2000-1-1 0:0:0\" ",
205
" -a title,global,o,c,\"MODIS Cloud Product (MOD06) Climatology\" ",
206
" -a institution,global,o,c,\"Yale University\" ",
207
" -a source,global,o,c,\"MODIS Cloud Product (MOD06)\" ",
208
" -a comment,global,o,c,\"Compiled by Adam M. Wilson (adam.wilson@yale.edu)\" ",
209
outdir2,"/MOD06_",tile,".nc",sep=""))
210

  
211

  
212
print(paste("###############################  Processed ",nrow(fdly),"days for tile:",tile," ###################################################"))
213
print("Years:")
214
print(table(fdly$fyear))
215
print("Months:")
216
print(table(fdly$fmonth))
217

  
218
## quit R
219
q("no")
220
 
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

  
23
### set options for Raster Package
24
setOptions(progress="text",timer=T)
25

  
26
X11.options(type="Xlib")
27
ncores=20  #number of threads to use
28

  
29
setwd("/home/adamw/personal/projects/interp")
30
setwd("/home/adamw/acrobates/projects/interp")
31

  
32
## read in shapefile as Region of Interest (roi)
33
roi=readOGR("data/regions/Test_sites/Oregon.shp","Oregon")
34
roi=spTransform(roi,CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0"))
35

  
36
### use MODIS tile as ROI instead
37
modt=readOGR("/home/adamw/acrobates/Global/modis_sinusoidal","modis_sinusoidal_grid_world",)
38
tiles=c("H9V4") #oregon
39
tiles=c("H11V8") #Venezuela
40

  
41
roi=modt[modt$HV%in%tiles,]
42

  
43
## Bounding box of region in lat/lon
44
roi_ll=spTransform(roi,CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
45
roi_bb=bbox(roi_ll)
46
     
47
### Downloading data from LAADSWEB
48
# subset by geographic area of interest
49

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

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

  
54
## specify some working directories
55
gdir="output/"
56
#datadir="data/modis/MOD06_L2_hdf"
57
#outdir="data/modis/MOD06_L2_hdf2"
58
#tifdir="/media/data/MOD06_L2_tif"
59
#summarydatadir="data/modis/MOD06_climatologies"
60
datadir="data/modis/Venezuela/MOD06"
61
outdir="data/modis/Venezuela/MOD06_"
62
#tifdir="/media/data/MOD06_L2_tif"
63
summarydatadir="data/modis/MOD06_climatologies"
64

  
65

  
66
fs=data.frame(
67
  path=list.files(datadir,full=T,recursive=T,pattern="hdf"),
68
  file=basename(list.files(datadir,full=F,recursive=T,pattern="hdf")))
69
fs$date=as.Date(substr(fs$file,11,17),"%Y%j")
70
fs$month=format(fs$date,"%m")
71
fs$year=format(fs$date,"%Y")
72
fs$time=substr(fs$file,19,22)
73
fs$datetime=as.POSIXct(strptime(paste(substr(fs$file,11,17),substr(fs$file,19,22)), '%Y%j %H%M'))
74
fs$dateid=format(fs$date,"%Y%m%d")
75
fs$path=as.character(fs$path)
76
fs$file=as.character(fs$file)
77

  
78
## output ROI
79
#get bounding box of region in m
80
#ge=SpatialPoints(data.frame(lon=c(-125,-115),lat=c(40,47)))
81
#projection(ge)=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
82
#ge2=spTransform(ge, CRS(" +proj=sinu +lon_0=0 +x_0=0 +y_0=0"))
83

  
84
## vars
85
vars=as.data.frame(matrix(c(
86
  "Cloud_Effective_Radius",              "CER",
87
  "Cloud_Effective_Radius_Uncertainty",  "CERU",
88
  "Cloud_Optical_Thickness",             "COT",
89
  "Cloud_Optical_Thickness_Uncertainty", "COTU",
90
  "Cloud_Water_Path",                    "CWP",
91
  "Cloud_Water_Path_Uncertainty",        "CWPU",
92
  "Cloud_Phase_Optical_Properties",      "CPOP",
93
  "Cloud_Multi_Layer_Flag",              "CMLF",
94
  "Cloud_Mask_1km",                      "CM1",
95
  "Quality_Assurance_1km",               "QA"),
96
  byrow=T,ncol=2,dimnames=list(1:10,c("variable","varid"))),stringsAsFactors=F)
97

  
98

  
99
### Installation of hegtool
100
## needed 32-bit libraries and java for program to install correctly
101

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

  
104

  
105
#### Function to generate hegtool parameter file for multi-band HDF-EOS file
106
swath2grid=function(i=1,files,vars,outdir,upleft,lowright){
107
  file=fs$path[i]
108
  print(paste("Starting file",basename(file)))
109
  outfile=paste(outdir,"/",fs$file[i],sep="")
110
### First write the parameter file (careful, heg is very finicky!)
111
  hdr=paste("NUM_RUNS = ",length(vars),"|MULTI_BAND_HDFEOS:",length(vars),sep="")
112
  grp=paste("
113
BEGIN
114
INPUT_FILENAME=",file,"
115
OBJECT_NAME=mod06
116
FIELD_NAME=",vars,"|
117
BAND_NUMBER = 1
118
OUTPUT_PIXEL_SIZE_X=1000
119
OUTPUT_PIXEL_SIZE_Y=1000
120
SPATIAL_SUBSET_UL_CORNER = ( ",upleft," )
121
SPATIAL_SUBSET_LR_CORNER = ( ",lowright," )
122
#RESAMPLING_TYPE =",ifelse(grepl("Flag|Mask|Quality",vars),"NN","CUBIC"),"
123
RESAMPLING_TYPE =NN
124
OUTPUT_PROJECTION_TYPE = UTM
125
UTM_ZONE = 10
126
# OUTPUT_PROJECTION_PARAMETERS = ( 6371007.181 0.0 0.0 0.0 0.0 0.0 0.0 0.0 86400.0 0.0 1.0 0.0 0.0 0.0 0.0 )
127
# projection parameters from http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/newPage.cgi?fileName=is_gctp
128
ELLIPSOID_CODE = WGS84
129
OUTPUT_TYPE = HDFEOS
130
OUTPUT_FILENAME = ",outfile,"
131
END
132

  
133
",sep="")
134
  
135
  ## if any remnants from previous runs remain, delete them
136
  if(length(list.files(tempdir(),pattern=basename(file)))>0)
137
    file.remove(list.files(tempdir(),pattern=basename(file),full=T))
138
  ## write it to a file
139
  cat(c(hdr,grp)    , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
140
  ## now run the swath2grid tool
141
  ## write the tiff file
142
  log=system(paste("sudo MRTDATADIR=/usr/local/heg/data ",
143
    "PGSHOME=/usr/local/heg/TOOLKIT_MTD PWD=/home/adamw /usr/local/heg/bin/swtif -p ",
144
    paste(tempdir(),"/",basename(file),"_MODparms.txt -d",sep=""),sep=""),intern=T)
145
      print(paste("Finished ", file))
146
}
147
 
148

  
149
### update fs with completed files
150
fs$complete=fs$file%in%list.files(outdir,pattern="hdf$")
151
table(fs$complete)
152

  
153
## must be run as root to access the data directory!  argh!
154
## run sudo once here to enter password before continuing
155
system('sudo ls')
156

  
157
#### Run the gridding procedure
158
mclapply(which(!fs$complete),function(fi){
159
  swath2grid(fi,vars=vars$variable,files=fs,
160
             outdir=outdir,
161
             upleft=paste(roi_bb[2,2],roi_bb[1,1]),
162
             lowright=paste(roi_bb[2,1],roi_bb[1,2]))},
163
         mc.cores=24)
164

  
165

  
166
##############################################################
167
### Import to GRASS for processing
168

  
169
#fs$grass=paste(fs$month,fs$year,fs$file,sep="_")
170
td=readGDAL(paste("HDF4_EOS:EOS_GRID:\"",outdir,"/",fs$file[1],"\":mod06:Cloud_Mask_1km_0",sep=""))
171
#projection(td)="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs +datum=WGS84 +ellps=WGS84 "
172
projection(td)="+proj=utm +zone=10 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
173

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

  
179
### create (or connect to) grass location
180
gisDbase="/media/data/grassdata"
181
gisLocation="oregon"
182
gisMapset="mod06"
183
## set Grass to overwrite
184
Sys.setenv(GRASS_OVERWRITE=1)
185
Sys.setenv(DEBUG=0)
186

  
187
## temporary objects to test function below
188
 i=1
189
file=paste(outdir,"/",fs$file[1],sep="")
190
date=as.Date("2000-05-23")
191

  
192

  
193
### Function to extract various SDSs from a single gridded HDF file and use QA data to throw out 'bad' observations
194
loadcloud<-function(date,fs){
195
### set up unique grass session
196
  tf=paste(tempdir(),"/grass", Sys.getpid(),"/", sep="")
197
 
198
  ## set up tempfile for this PID
199
  initGRASS(gisBase="/usr/lib/grass64",gisDbase=tf,SG=td,override=T,location="mod06",mapset="PERMANENT",home=tf,pid=Sys.getpid())
200
#  system(paste("g.proj -c proj4=\"+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +datum=WGS84 +units=m +no_defs\"",sep=""))
201
    system(paste("g.proj -c proj4=\"+proj=utm +zone=10 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\"",sep=""))
202

  
203
  ## Define region by importing one raster.
204
  execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",outdir,"/",fs$file[1],"\":mod06:Cloud_Mask_1km_0",sep=""),
205
            output="modisgrid",flags=c("quiet","overwrite","o"))
206
  system("g.region rast=modisgrid save=roi --overwrite")
207
  system("g.region roi")
208
  system("g.region -p")
209

  
210
  ## Identify which files to process
211
  tfs=fs$file[fs$date==date]
212
  nfs=length(tfs)
213

  
214
  ### print some summary info
215
  print(date)
216
  ## loop through scenes and process QA flags
217
  for(i in 1:nfs){
218
     file=paste(outdir,"/",tfs[i],sep="")
219
     ## Cloud Mask
220
     execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Mask_1km_0",sep=""),
221
              output=paste("CM1_",i,sep=""),flags=c("overwrite","o")) ; print("")
222
    ## extract cloudy and 'confidently clear' pixels
223
    system(paste("r.mapcalc <<EOF
224
                CM_cloud_",i," =  ((CM1_",i," / 2^0) % 2) == 1  &&  ((CM1_",i," / 2^1) % 2^2) == 0 
225
                CM_clear_",i," =  ((CM1_",i," / 2^0) % 2) == 1  &&  ((CM1_",i," / 2^1) % 2^2) == 3 
226
EOF",sep=""))
227

  
228
    ## QA
229
    execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Quality_Assurance_1km_0",sep=""),
230
             output=paste("QA_",i,sep=""),flags=c("overwrite","o")) ; print("")
231
   ## QA_CER
232
   system(paste("r.mapcalc <<EOF
233
                 QA_COT_",i,"=   ((QA_",i," / 2^0) % 2^1 )==1
234
                 QA_COT2_",i,"=  ((QA_",i," / 2^1) % 2^2 )==3
235
                 QA_COT3_",i,"=  ((QA_",i," / 2^3) % 2^2 )==0
236
                 QA_CER_",i,"=   ((QA_",i," / 2^5) % 2^1 )==1
237
                 QA_CER2_",i,"=  ((QA_",i," / 2^6) % 2^2 )==3
238
EOF",sep="")) 
239
#                 QA_CWP_",i,"=   ((QA_",i," / 2^8) % 2^1 )==1
240
#                 QA_CWP2_",i,"=  ((QA_",i," / 2^9) % 2^2 )==3
241

  
242
   ## Optical Thickness
243
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Optical_Thickness",sep=""),
244
            output=paste("COT_",i,sep=""),
245
            title="cloud_effective_radius",
246
            flags=c("overwrite","o")) ; print("")
247
   execGRASS("r.null",map=paste("COT_",i,sep=""),setnull="-9999")
248
   ## keep only positive COT values where quality is 'useful' and 'very good' & scale to real units
249
   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=""))   
250
   ## set COT to 0 in clear-sky pixels
251
   system(paste("r.mapcalc \"COT2_",i,"=if(CM_clear_",i,"==0,COT_",i,",0)\"",sep=""))   
252
   
253
   ## Effective radius ##
254
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Effective_Radius",sep=""),
255
            output=paste("CER_",i,sep=""),
256
            title="cloud_effective_radius",
257
            flags=c("overwrite","o")) ; print("")
258
   execGRASS("r.null",map=paste("CER_",i,sep=""),setnull="-9999")
259
   ## keep only positive CER values where quality is 'useful' and 'very good' & scale to real units
260
   system(paste("r.mapcalc \"CER_",i,"=if(QA_CER_",i,"&&QA_CER2_",i,"&&CER_",i,">=0,CER_",i,"*0.009999999776482582,null())\"",sep=""))   
261
   ## set CER to 0 in clear-sky pixels
262
   system(paste("r.mapcalc \"CER2_",i,"=if(CM_clear_",i,"==0,CER_",i,",0)\"",sep=""))   
263

  
264
   ## Cloud Water Path
265
#   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Water_Path",sep=""),
266
#            output=paste("CWP_",i,sep=""),title="cloud_water_path",
267
#            flags=c("overwrite","o")) ; print("")
268
#   execGRASS("r.null",map=paste("CWP_",i,sep=""),setnull="-9999")
269
   ## keep only positive CER values where quality is 'useful' and 'very good' & scale to real units
270
#   system(paste("r.mapcalc \"CWP_",i,"=if(QA_CWP_",i,"&&QA_CWP2_",i,"&&CWP_",i,">=0,CWP_",i,"*0.009999999776482582,null())\"",sep=""))   
271
   ## set CER to 0 in clear-sky pixels
272
#   system(paste("r.mapcalc \"CWP2_",i,"=if(CM_clear_",i,"==0,CWP_",i,",0)\"",sep=""))   
273
     
274
 } #end loop through sub daily files
275

  
276
#### Now generate daily averages (or maximum in case of cloud flag)
277
  
278
  system(paste("r.mapcalc <<EOF
279
         COT_denom=",paste("!isnull(COT2_",1:nfs,")",sep="",collapse="+"),"
280
         COT_numer=",paste("if(isnull(COT2_",1:nfs,"),0,COT2_",1:nfs,")",sep="",collapse="+"),"
281
         COT_daily=COT_numer/COT_denom
282
         CER_denom=",paste("!isnull(CER2_",1:nfs,")",sep="",collapse="+"),"
283
         CER_numer=",paste("if(isnull(CER2_",1:nfs,"),0,CER2_",1:nfs,")",sep="",collapse="+"),"
284
         CER_daily=CER_numer/CER_denom
285
         CLD_daily=max(",paste("if(isnull(CM_cloud_",1:nfs,"),0,CM_cloud_",1:nfs,")",sep="",collapse=","),") 
286
EOF",sep=""))
287

  
288
  #### Write the files to a geotiff
289
  execGRASS("r.out.gdal",input="CER_daily",output=paste(tifdir,"/CER_",format(date,"%Y%m%d"),".tif",sep=""),nodata=-999,flags=c("quiet"))
290
  execGRASS("r.out.gdal",input="COT_daily",output=paste(tifdir,"/COT_",format(date,"%Y%m%d"),".tif",sep=""),nodata=-999,flags=c("quiet"))
291
  execGRASS("r.out.gdal",input="CLD_daily",output=paste(tifdir,"/CLD_",format(date,"%Y%m%d"),".tif",sep=""),nodata=99,flags=c("quiet"))
292

  
293
### delete the temporary files 
294
  unlink_.gislock()
295
  system("/usr/lib/grass64/etc/clean_temp")
296
 system(paste("rm -R ",tf,sep=""))
297
### print update
298
  print(paste(" ###################################################################               Finished ",date,"
299
################################################################"))
300
}
301

  
302

  
303
###########################################
304
### Now run it
305

  
306
tdates=sort(unique(fs$date))
307
done=tdates%in%as.Date(substr(list.files(tifdir),5,12),"%Y%m%d")
308
table(done)
309
tdates=tdates[!done]
310

  
311
mclapply(tdates,function(date) loadcloud(date,fs=fs))
312

  
313
 
314

  
315
#######################################################################################33
316
###  Produce the monthly averages
317

  
318
## get list of daily files
319
fs2=data.frame(
320
  path=list.files(tifdir,full=T,recursive=T,pattern="tif$"),
321
  file=basename(list.files(tifdir,full=F,recursive=T,pattern="tif$")))
322
fs2$type=substr(fs2$file,1,3)
323
fs2$date=as.Date(substr(fs2$file,5,12),"%Y%m%d")
324
fs2$month=format(fs2$date,"%m")
325
fs2$year=format(fs2$date,"%Y")
326
fs2$path=as.character(fs2$path)
327
fs2$file=as.character(fs2$file)
328

  
329

  
330
# Define type/month products
331
vs=expand.grid(type=unique(fs2$type),month=c("01","02","03","04","05","06","07","08","09","10","11","12"))
332

  
333
## identify which have been completed
334
done.vs=unique(do.call(rbind,strsplit(list.files(summarydatadir),"_|[.]"))[,c(1,3)])
335
done.vs=paste(vs$type,vs$month,sep="_")%in%paste(done.vs[,1],done.vs[,2],sep="_")
336
table(done.vs)
337
vs=vs[!done.vs,]
338

  
339
#tfs=fs2$path[which(fs2$month==vs$month[i]&fs2$type==vs$type[i])]
340
#do.call(c,mclapply(2:length(tfs),function(f) #identical(extent(raster(tfs[f-1])),extent(raster(tfs[f])))))
341
#raster(tfs[23])
342

  
343
## process the monthly summaries using the raster package
344
mclapply(1:nrow(vs),function(i){
345
  print(paste("Loading ",vs$type[i]," for month ",vs$month[i]))
346
  td=stack(fs2$path[which(fs2$month==vs$month[i]&fs2$type==vs$type[i])])
347
  print(paste("Processing Metric ",vs$type[i]," for month ",vs$month[i]))
348
  calc(td,mean,na.rm=T,
349
       filename=paste(summarydatadir,"/",vs$type[i],"_mean_",vs$month[i],".tif",sep=""),
350
       format="GTiff",overwrite=T)
351
  calc(td,sd,na.rm=T,
352
       filename=paste(summarydatadir,"/",vs$type[i],"_sd_",vs$month[i],".tif",sep=""),
353
       format="GTiff",overwrite=T)
354
  if(vs$type[i]%in%c("CER")) {
355
    ## Calculate number of days with effective radius > 20um, found to be linked to precipitating clouds
356
    ## (Kobayashi 2007)
357
    calc(td,function(x) mean(ifelse(x<20,0,1),na.rm=T),
358
      filename=paste(summarydatadir,"/",vs$type[i],"_P20um_",vs$month[i],".tif",sep=""),
359
      format="GTiff",overwrite=T)
360
#    td2[td2<20]=0
361
#    td2[td2>=20]=1
362
#    calc(td2,mean,na.rm=T,
363
#         filename=paste(summarydatadir,"/",vs$type[i],"_P20um_",vs$month[i],".tif",sep=""),
364
#         format="GTiff",overwrite=T)
365
  }  
366
  print(paste("Processing missing data for ",vs$type[i]," for month ",vs$month[i]))
367
  calc(td,function(i)
368
       sum(!is.na(i)),filename=paste(summarydatadir,"/",vs$type[i],"_count_",vs$month[i],".tif",sep=""),
369
       format="GTiff",overwrite=T)
370
  calc(td,function(i) sum(ifelse(i==0,0,1)),
371
       filename=paste(summarydatadir,"/",vs$type[i],"_clear_",vs$month[i],".tif",sep=""),format="GTiff",overwrite=T)
372
  gc()
373
}
374
)
375

  
376

  
377
vs[c(10:18,22:24,34:36),]
378

  
379
#### reproject to Oregon state plane for easy comparison with Benoit's data
380
dest=raster("data/regions/oregon/lulc/W_Layer1_ClippedTo_OR83M.rst")  # choose one to match (projection, resolution, extent)
381
projection(dest)=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 +units=m +no_defs") #define projection
382
tifs=list.files(summarydatadir,pattern="*.tif$",full=T) #get list of files to process
383
mclapply(tifs,function(f) projectRaster(raster(f),dest,filename=paste(dirname(f),"/OR03M_",basename(f),sep=""),overwrite=T))  # warp them
384

  
385

  
386

  
climate/procedures/MOD06_L2_data_compile_Pleiades.r
1
###################################################################################
2
###  R code to aquire and process MOD06_L2 cloud data from the MODIS platform
3

  
4

  
5
##First read in the arguments listed at the command line
6
args=(commandArgs(TRUE))
7
##args is now a list of character vectors
8
## First check to see if arguments are passed.
9
## if no args were given, print a warning and stop
10
if(length(args)==0) {stop("No parameters supplied, you must pass parameters")}
11

  
12
## Then cycle through each element of the list and evaluate the expressions.
13
eval(parse(text=args))
14
## now there is an i that corresponds to the row in the notdone object that will be processed.
15

  
16
## load libraries
17
require(sp)
18
require(rgdal)
19
require(reshape)
20
require(ncdf4)
21
require(geosphere)
22
require(raster)
23
require(spgrass6)
24

  
25
## specify some working directories
26
setwd("/nobackupp1/awilso10/mod06")
27
tempdir=tempdir()  # to hold intermediate files
28
outdir="2_daily"   # final daily product
29
tile="h11v08"   #can move this to submit script if needed
30
## read in list of all files
31
load("allfiles.Rdata")
32
load("notdone.Rdata")
33
load("vars.Rdata")
34

  
35
date=notdone[i]
36
#file=fs$path[fs$dateid==date][1]
37

  
38
## print out some info
39
print(paste("Processing date ",date," for tile",tile))
40

  
41
## identify tile of interest
42
tile_bb=tb[tb$tile==tile,]
43

  
44
#### Function to generate hegtool parameter file for multi-band HDF-EOS file
45
swath2grid=function(file,vars,upleft,lowright){
46
  print(paste("Starting file",basename(file)))
47
  outfile=paste(tempdir(),"/",basename(file),sep="")
48
### First write the parameter file (careful, heg is very finicky!)
49
  hdr=paste("NUM_RUNS = ",length(vars$varid),"|MULTI_BAND_HDFEOS:",length(vars$varid),sep="")
50
  grp=paste("
51
BEGIN
52
INPUT_FILENAME=",file,"
53
OBJECT_NAME=mod06
54
FIELD_NAME=",vars$variable,"|
55
BAND_NUMBER = 1
56
OUTPUT_PIXEL_SIZE_X=1000
57
OUTPUT_PIXEL_SIZE_Y=1000
58
SPATIAL_SUBSET_UL_CORNER = ( ",upleft," )
59
SPATIAL_SUBSET_LR_CORNER = ( ",lowright," )
60
#RESAMPLING_TYPE =",ifelse(grepl("Flag|Mask|Quality",vars),"NN","CUBIC"),"
61
RESAMPLING_TYPE =NN
62
OUTPUT_PROJECTION_TYPE = SIN
63
#UTM_ZONE = 10
64
 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 )
65
# projection parameters from http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/newPage.cgi?fileName=sn_gctp
66
ELLIPSOID_CODE = WGS84
67
OUTPUT_TYPE = HDFEOS
68
OUTPUT_FILENAME = ",outfile,"
69
END
70

  
71
",sep="")
72
 
73
  ## if any remnants from previous runs remain, delete them
74
  if(length(list.files(tempdir(),pattern=basename(file)))>0)
75
    file.remove(list.files(tempdir(),pattern=basename(file),full=T))
76
  ## write it to a file
77
  cat(c(hdr,grp)    , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
78
  ## now run the swath2grid tool
79
  ## write the tiff file
80
  log=system(paste("/nobackupp4/pvotava/software/heg/bin/swtif -p ",paste(tempdir(),"/",basename(file),"_MODparms.txt -d",sep=""),sep=""),intern=T)
81
  ## clean up temporary files in working directory
82
#  file.remove(paste("filetable.temp_",pid,sep=""))
83
  print(log)
84
  print(paste("Finished ", file))
85
}
86

  
87
#### Run the gridding procedure
88
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))
89
#upleft=paste(roi_bb[2,2],roi_bb[1,1]),lowright=paste(roi_bb[2,1],roi_bb[1,2]))
90

  
91

  
92
##############################################################
93
### Import to GRASS for processing
94

  
95
#fs$grass=paste(fs$month,fs$year,fs$file,sep="_")
96
#td=readGDAL(paste("HDF4_EOS:EOS_GRID:\"",outdir,"/",fs$file[1],"\":mod06:Cloud_Mask_1km_0",sep=""))
97

  
98
gridfile=list.files("/nobackupp4/datapool/modis/MOD11A1.005/2006.01.27/",pattern=paste(tile,".*hdf$",sep=""),full=T)
99
td=readGDAL(paste("HDF4_EOS:EOS_GRID:\"",gridfile,"\":MODIS_Grid_Daily_1km_LST:Night_view_angl",sep=""))
100
projection(td)="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs +datum=WGS84 +ellps=WGS84 "
101

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

  
107
### create (or connect to) grass location
108
gisLocation="tmp"
109
gisMapset="mod06"
110
## set Grass to overwrite
111
Sys.setenv(GRASS_OVERWRITE=1)
112
Sys.setenv(DEBUG=1)
113
Sys.setenv(GRASS_GUI="txt")
114

  
115
## temporary objects to test function below
116
# i=1
117
#file=paste(outdir,"/",fs$file[1],sep="")
118
#date=as.Date("2000-05-23")
119

  
120
#.GRASS_CACHE=spgrass6:::.GRASS_CACHE
121

  
122
### Function to extract various SDSs from a single gridded HDF file and use QA data to throw out 'bad' observations
123
loadcloud<-function(date,fs){
124
  tf=paste(tempdir(),"/grass", Sys.getpid(),"/", sep="")
125
  print(paste("Set up temporary grass session in",tf))
126
 
127
  ## set up temporary grass instance for this PID
128
  initGRASS(gisBase="/nobackupp1/awilso10/software/grass-6.4.3svn",gisDbase=tf,SG=td,override=T,location="mod06",mapset="PERMANENT",home=tf,pid=Sys.getpid())
129
  system(paste("g.proj -c proj4=\"",projection(td),"\"",sep=""))
130

  
131
  ## Define region by importing one MOD11A1 raster.
132
  print("Import one MOD11A1 raster to define grid")
133
  execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",gridfile,"\":MODIS_Grid_Daily_1km_LST:Night_view_angl",sep=""),
134
            output="modisgrid",flags=c("quiet","overwrite","o"))
135
  system("g.region rast=modisgrid save=roi --overwrite")
136

  
137
  ## Identify which files to process
138
  tfs=fs$file[fs$dateid==date]
139
  nfs=length(tfs)
140

  
141
  ## loop through scenes and process QA flags
142
  for(i in 1:nfs){
143
     file=paste(tempdir,"/",tfs[i],sep="")
144
     ## Cloud Mask
145
     execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Mask_1km_0",sep=""),
146
              output=paste("CM1_",i,sep=""),flags=c("overwrite","o")) ; print("")
147
    ## extract cloudy and 'confidently clear' pixels
148
    system(paste("r.mapcalc <<EOF
149
                CM_cloud_",i," =  ((CM1_",i," / 2^0) % 2) == 1  &&  ((CM1_",i," / 2^1) % 2^2) == 0 
150
                CM_clear_",i," =  ((CM1_",i," / 2^0) % 2) == 1  &&  ((CM1_",i," / 2^1) % 2^2) == 3 
151
EOF",sep=""))
152

  
153
    ## QA
154
     execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Quality_Assurance_1km_0",sep=""),
155
             output=paste("QA_",i,sep=""),flags=c("overwrite","o")) ; print("")
156
   ## QA_CER
157
   system(paste("r.mapcalc <<EOF
158
                 QA_COT_",i,"=   ((QA_",i," / 2^0) % 2^1 )==1
159
                 QA_COT2_",i,"=  ((QA_",i," / 2^1) % 2^2 )==3
160
                 QA_COT3_",i,"=  ((QA_",i," / 2^3) % 2^2 )==0
161
                 QA_CER_",i,"=   ((QA_",i," / 2^5) % 2^1 )==1
162
                 QA_CER2_",i,"=  ((QA_",i," / 2^6) % 2^2 )==3
163
EOF",sep="")) 
164
#                 QA_CWP_",i,"=   ((QA_",i," / 2^8) % 2^1 )==1
165
#                 QA_CWP2_",i,"=  ((QA_",i," / 2^9) % 2^2 )==3
166

  
167
   ## Optical Thickness
168
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Optical_Thickness",sep=""),
169
            output=paste("COT_",i,sep=""),
170
            title="cloud_effective_radius",
171
            flags=c("overwrite","o")) ; print("")
172
   execGRASS("r.null",map=paste("COT_",i,sep=""),setnull="-9999")
173
   ## keep only positive COT values where quality is 'useful' and 'very good' & scale to real units
174
   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=""))   
175
   ## set COT to 0 in clear-sky pixels
176
   system(paste("r.mapcalc \"COT2_",i,"=if(CM_clear_",i,"==0,COT_",i,",0)\"",sep=""))   
177
   
178
   ## Effective radius ##
179
   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Effective_Radius",sep=""),
180
            output=paste("CER_",i,sep=""),
181
            title="cloud_effective_radius",
182
            flags=c("overwrite","o")) ; print("")
183
   execGRASS("r.null",map=paste("CER_",i,sep=""),setnull="-9999")
184
   ## keep only positive CER values where quality is 'useful' and 'very good' & scale to real units
185
   system(paste("r.mapcalc \"CER_",i,"=if(QA_CER_",i,"&&QA_CER2_",i,"&&CER_",i,">=0,CER_",i,"*0.009999999776482582,null())\"",sep=""))   
186
   ## set CER to 0 in clear-sky pixels
187
   system(paste("r.mapcalc \"CER2_",i,"=if(CM_clear_",i,"==0,CER_",i,",0)\"",sep=""))   
188

  
189
   ## Cloud Water Path
190
#   execGRASS("r.in.gdal",input=paste("HDF4_EOS:EOS_GRID:\"",file,"\":mod06:Cloud_Water_Path",sep=""),
191
#            output=paste("CWP_",i,sep=""),title="cloud_water_path",
192
#            flags=c("overwrite","o")) ; print("")
193
#   execGRASS("r.null",map=paste("CWP_",i,sep=""),setnull="-9999")
194
   ## keep only positive CER values where quality is 'useful' and 'very good' & scale to real units
195
#   system(paste("r.mapcalc \"CWP_",i,"=if(QA_CWP_",i,"&&QA_CWP2_",i,"&&CWP_",i,">=0,CWP_",i,"*0.009999999776482582,null())\"",sep=""))   
196
   ## set CER to 0 in clear-sky pixels
197
#   system(paste("r.mapcalc \"CWP2_",i,"=if(CM_clear_",i,"==0,CWP_",i,",0)\"",sep=""))   
198
     
199
 } #end loop through sub daily files
200

  
201
#### Now generate daily averages (or maximum in case of cloud flag)
202
  
203
  system(paste("r.mapcalc <<EOF
204
         COT_denom=",paste("!isnull(COT2_",1:nfs,")",sep="",collapse="+"),"
205
         COT_numer=",paste("if(isnull(COT2_",1:nfs,"),0,COT2_",1:nfs,")",sep="",collapse="+"),"
206
         COT_daily=COT_numer/COT_denom
207
         CER_denom=",paste("!isnull(CER2_",1:nfs,")",sep="",collapse="+"),"
208
         CER_numer=",paste("if(isnull(CER2_",1:nfs,"),0,CER2_",1:nfs,")",sep="",collapse="+"),"
209
         CER_daily=CER_numer/CER_denom
210
         CLD_daily=max(",paste("if(isnull(CM_cloud_",1:nfs,"),0,CM_cloud_",1:nfs,")",sep="",collapse=","),") 
211
EOF",sep=""))
212

  
213
  #### Write the files to a geotiff
214
  execGRASS("r.out.gdal",input="CER_daily",output=paste(outdir,"/CER_",date,".tif",sep=""),nodata=-999,flags=c("quiet"))
215
  execGRASS("r.out.gdal",input="COT_daily",output=paste(outdir,"/COT_",date,".tif",sep=""),nodata=-999,flags=c("quiet"))
216
  execGRASS("r.out.gdal",input="CLD_daily",output=paste(outdir,"/CLD_",date,".tif",sep=""),nodata=99,flags=c("quiet"))
217

  
218
### delete the temporary files 
219
  unlink_.gislock()
220
  system("/nobackupp1/awilso10/software/grass-6.4.3svn/etc/clean_temp")
221
  system(paste("rm -R ",tf,sep=""))
222
### print update
223
}
224

  
225

  
226
###########################################
227
### Now run it
228

  
229
lapply(date,function(date) loadcloud(date,fs=fs))
230

  
231

  
232

  
233
  print(paste(" ###################################################################               Finished ",date,"
234
################################################################"))
235

  
236

  
237
## quit R
238
q("no")
239
 
240

  
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

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff