Project

General

Profile

Download (8.23 KB) Statistics
| Branch: | Revision:
1
############################
2
####  Extract MOD35 C6 processing path
3

    
4
setwd("~/acrobates/adamw/projects/interp/data/modis/mod35")
5
library(multicore)
6
library(raster)
7
library(spgrass6)
8
library(rgeos)
9
##download 3 days of modis swath data:
10

    
11
url="ftp://ladsweb.nascom.nasa.gov/allData/51/MOD35_L2/2012/"
12
dir.create("swath")
13

    
14
system(paste("wget -S --recursive --no-parent --no-directories -N -P swath --accept \"hdf\" --accept \"002|003|004\" ",url))
15

    
16

    
17
### make global raster that aligns with MODLAND tiles
18
## get MODLAND tile to serve as base
19
#system("wget http://e4ftl01.cr.usgs.gov/MOLT/MOD13A3.005/2000.02.01/MOD13A3.A2000032.h00v08.005.2006271174446.hdf")
20
#t=raster(paste("HDF4_EOS:EOS_GRID:\"",getwd(),"/MOD13A3.A2000032.h00v08.005.2006271174446.hdf\":MOD_Grid_monthly_1km_VI:1 km monthly NDVI",sep=""))
21
t=raster(paste("../MOD17/MOD17A3_Science_NPP_mean_00_12.tif",sep=""))
22
projection(t)
23

    
24
## make global extent
25
pmodis="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs"
26

    
27
glb=t
28
#values(glb)=NA
29
glb=extend(glb,extent(-180,180,-90,90))
30

    
31
#glb=raster(glb,crs="+proj=longlat +datum=WGS84",nrows=42500,ncols=85000)
32
#extent(glb)=alignExtent(projectRaster(glb,crs=projection(t),over=T),t)
33
#res(glb)=c(926.6254,926.6264)
34
#projection(glb)=pmodis
35

    
36
## confirm extent
37
#projectExtent(glb,crs="+proj=longlat +datum=WGS84")
38

    
39

    
40
#### Grid and mosaic the swath data
41

    
42
stitch="sudo MRTDATADIR=\"/usr/local/heg/2.12/data\" PGSHOME=/usr/local/heg/2.12/TOOLKIT_MTD PWD=/home/adamw /usr/local/heg/2.12/bin/swtif"
43
stitch="/usr/local/heg/2.12/bin/swtif"
44

    
45
#stitch="sudo MRTDATADIR=\"/usr/local/heg/2.11/data\" PGSHOME=/usr/local/heg/2.11/TOOLKIT_MTD PWD=/home/adamw /usr/local/heg/2.11/bin/swtif"
46
#files=paste(getwd(),"/",list.files("swath",pattern="hdf$",full=T),sep="")
47

    
48
## vars to process
49
vars=as.data.frame(matrix(c(
50
  "Cloud_Mask",           "CM",   "NN",    1,
51
#  "Sensor_Azimuth",       "ZA",   "CUBIC", 1,
52
  "Sensor_Zenith",        "SZ",   "CUBIC", 1),
53
  byrow=T,ncol=4,dimnames=list(1:2,c("variable","varid","method","band"))),stringsAsFactors=F)
54

    
55
## global bounding box
56
   gbb=cbind(c(-180,-180,180,180,-180),c(-90,90,90,-90,-90))
57
   gpp = SpatialPolygons(list(Polygons(list(Polygon(gbb)),1)))
58
   proj4string(gpp)=projection(glb)
59

    
60
outdir="~/acrobates/adamw/projects/interp/data/modis/mod35/gridded/"
61

    
62
swtif<-function(file,var){
63
  outfile=paste(tempdir(),"/",var$varid,"_",basename(file),sep="")  #gridded path
64
   ## First write the parameter file (careful, heg is very finicky!)
65
   hdr=paste("NUM_RUNS = 1")
66
   grp=paste("
67
BEGIN
68
INPUT_FILENAME=",file,"
69
OBJECT_NAME=mod35
70
FIELD_NAME=",var$variable,"|
71
BAND_NUMBER = ",var$band,"
72
OUTPUT_PIXEL_SIZE_X=0.008333333
73
OUTPUT_PIXEL_SIZE_Y=0.008333333
74
SPATIAL_SUBSET_UL_CORNER = ( ",bbox(gpp)[2,2]," ",bbox(gpp)[1,1]," )
75
SPATIAL_SUBSET_LR_CORNER = ( ",bbox(gpp)[2,1]," ",bbox(gpp)[1,2]," )
76
RESAMPLING_TYPE =",var$method,"
77
OUTPUT_PROJECTION_TYPE = GEO
78
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 )
79
# 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 )
80
# projection parameters from http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/newPage.cgi?fileName=sn_gctp
81
ELLIPSOID_CODE = WGS84
82
OUTPUT_TYPE = HDFEOS
83
OUTPUT_FILENAME= ",outfile,"
84
END
85

    
86
",sep="")
87
   ## write it to a file
88
   cat( c(hdr,grp)   , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
89
   ## now run the swath2grid tool
90
   ## write the gridded file
91
   print(paste("Starting",file))
92
   system(paste("",stitch," -p ",tempdir(),"/",basename(file),"_MODparms.txt -d -log /dev/null ",sep=""),intern=F)#,ignore.stderr=F)
93
   print(paste("Finished processing variable",var$variable,"from ",basename(file),"to",outfile))
94
}  
95

    
96
getpath<- function(file){  
97
   setwd(tempdir())
98
   bfile=sub(".hdf","",basename(file))
99
   tempfile2_path=paste(tempdir(),"/",bfile,".tif",sep="")  #gridded/masked/processed path
100
   outfile=paste(outdir,"/",bfile,".tif",sep="")  #final file
101
   if(file.exists(outfile)) return(c(file,0))
102
   ppc=gpp
103
#######
104
## run swtif for each band
105
   lapply(1:nrow(vars),function(i) swtif(file,vars[i,]))
106
####### import to R for processing
107
  
108
   if(!file.exists(paste(tempdir(),"/CM_",basename(file),sep=""))) {
109
     file.remove(list.files(tempdir(),pattern=bfile,full=T))
110
     return(c(file,0))
111
   }
112
   ## convert to land path
113
   d=raster(paste(tempdir(),"/CM_",basename(file),sep=""))
114
   sz=raster(paste(tempdir(),"/SZ_",basename(file),sep=""))
115
   NAvalue(sz)=-9999
116
   getlc=function(x,y) {ifelse(y==0|y>6000,NA,((x%/%2^6) %% 2^2))}
117
   path=  overlay(d,sz,fun=getlc,filename=tempfile2_path,options=c("COMPRESS=LZW", "LEVEL=9","PREDICTOR=2"),datatype="INT1U",overwrite=T)
118
### warp them to align all pixels
119
   system(paste("gdalwarp -overwrite -srcnodata 255 -dstnodata 255 -tap -tr 0.008333333 0.008333333 -co COMPRESS=LZW -co ZLEVEL=9 -co PREDICTOR=2 -s_srs \"",projection(t),"\" ",tempfile2_path," ",outfile,sep=""))
120
   ## delete temporary files
121
   file.remove(list.files(tempdir(),pattern=bfile,full=T))
122
   return(c(file,1))
123
 }
124

    
125

    
126
### run it
127
mclapply(files,getpath,mc.cores=10)
128

    
129
## check gdal can read all of them
130
gfiles=list.files(outdir,pattern="tif$",full=T)
131
length(gfiles)
132

    
133
check=do.call(rbind,mclapply(gfiles,function(file){
134
    gd=system(paste("gdalinfo ",file,sep=""),intern=T)
135
    if(any(grepl("Corner",gd))) return(1)
136
    else return(0)
137
}))
138

    
139
table(check)
140

    
141
file.remove(gfiles[check==0])
142

    
143
## use new gdal
144
system(paste("nohup /usr/local/gdal-1.10.0/bin/gdalwarp -wm 900 -overwrite -co COMPRESS=LZW -co PREDICTOR=2 -multi -r mode ",outdir,"/*.tif MOD35_path_gdalwarp.tif &",sep=""))
145

    
146

    
147
###  Merge them into a geotiff
148
    system(paste("gdal_merge.py -v -init 255 -n 255 -o ",outdir,"/../MOD35_ProcessPath_gdalmerge2.tif -co \"ZLEVEL=9\" -co \"COMPRESS=LZW\" -co \"PREDICTOR=2\" `ls -d -1 ",outdir,"/*.tif --sort=size `",sep=""))
149

    
150
#  origin(raster(gfiles[5]))
151
  
152
  ## try with pktools
153
  ## global
154
system(paste("pkmosaic -co COMPRESS=LZW -co PREDICTOR=2 ",paste("-i",list.files("gridded",full=T,pattern="tif$"),collapse=" ")," -o MOD35_path_pkmosaic_mode.tif  -m 6 -v -t 255 -t 0 &"))
155
#bb="-ulx -180 -uly 90 -lrx 180 -lry -90"
156
#bb="-ulx -180 -uly 90 -lrx 170 -lry 80"
157
bb="-ulx -72 -uly 11 -lrx -59 -lry -1"
158

    
159

    
160
#expand.grid(x=seq(-180,170,by=10),y=seq(-90,80))
161
gf2=  grep("2012009[.]03",gfiles,value=T)
162
system(paste("pkmosaic ",bb," -co COMPRESS=LZW -co PREDICTOR=2 ",paste("-i",gf2,collapse=" ")," -o h11v08_path_pkmosaic.tif -ot Byte -m 7 -v -t 255"))
163

    
164
                                        #  bounding box?  
165

    
166
###########
167
### Use GRASS to import all the tifs and calculat the mode
168
## make temporary working directory
169
  tf=paste(tempdir(),"/grass", Sys.getpid(),"/", sep="")  #temporar
170
  if(!file.exists(tf)) dir.create(tf)
171
  
172
  ## set up temporary grass instance for this PID
173
  gisBase="/usr/lib/grass64"
174
  print(paste("Set up temporary grass session in",tf))
175
  initGRASS(gisBase=gisBase,gisDbase=tf,SG=as(glb,"SpatialGridDataFrame"),override=T,location="mod35",mapset="PERMANENT",home=tf,pid=Sys.getpid())
176
  system(paste("g.proj -c proj4=\"",projection(glb),"\"",sep=""),ignore.stdout=T,ignore.stderr=T)
177

    
178
## read in NPP grid to serve as grid
179
  execGRASS("r.in.gdal",input=t@file@name,output="grid")
180
  system("g.region rast=grid n=90 s=-90 save=roi --overwrite",ignore.stdout=F,ignore.stderr=F)
181

    
182
## get files already imported - only important if more tifs were written after an initial import
183
imported=basename(gfiles)%in%system("g.mlist type=rast pattern=MOD*",intern=T)
184
table(imported)
185

    
186
## read in all tifs
187
  for(f in gfiles[!imported])  execGRASS("r.in.gdal",input=f,output=basename(f),flags="o")
188

    
189
## calculate mode
190
execGRASS("r.series",input=paste(system("g.mlist type=rast pattern=MOD*",intern=T)[1:1000],sep="",collapse=","),output="MOD35_path",method="mode",range=c(1,5),flags=c("verbose","overwrite"))
191
## add colors
192
execGRASS("r.colors",map="MOD35_path",rules="MOD35_path_grasscolors.txt")
193
## write to disk
194
execGRASS("r.out.gdal",input="MOD35_path",output=paste(getwd(),"/MOD35_ProcessPath_C5.tif",sep=""),type="Byte",createopt="COMPRESS=LZW,LEVEL=9,PREDICTOR=2")
195

    
196
### delete the temporary files 
197
  unlink_.gislock()
198
  system(paste("rm -frR ",tf,sep=""))
199

    
200
#########################
201

    
202

    
203
cols=c("blue","lightblue","tan","green")
204

    
205

    
206

    
207
## connect to raster to extract land-cover bit
208
library(raster)
209

    
210
d=raster("CM.tif")
211
getlc=function(x) {(x/2^6) %% 2^2}
212

    
213
calc(d,fun=getlc,filename="CM_LC.tif")
214

    
(22-22/35)