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/data\" PGSHOME=/usr/local/heg/TOOLKIT_MTD PWD=/home/adamw /usr/local/heg/bin/swtif"
|
43
|
|
44
|
files=paste(getwd(),"/",list.files("swath",pattern="hdf$",full=T),sep="")
|
45
|
|
46
|
## vars to process
|
47
|
vars=as.data.frame(matrix(c(
|
48
|
"Cloud_Mask", "CM",
|
49
|
"Sensor_Azimuth", "ZA",
|
50
|
"Sensor_Zenith", "SZ"),
|
51
|
byrow=T,ncol=2,dimnames=list(1:3,c("variable","varid"))),stringsAsFactors=F)
|
52
|
|
53
|
## global bounding box
|
54
|
gbb=cbind(c(-180,-180,180,180,-180),c(-85,85,85,-85,-85))
|
55
|
gpp = SpatialPolygons(list(Polygons(list(Polygon(gbb)),1)))
|
56
|
proj4string(gpp)=projection(glb)
|
57
|
|
58
|
|
59
|
getpath<- function(file){
|
60
|
setwd(tempdir())
|
61
|
bfile=sub(".hdf","",basename(file))
|
62
|
tempfile_path=paste(tempdir(),"/path_",basename(file),sep="") #gridded path
|
63
|
tempfile_sz=paste(tempdir(),"/sz_",basename(file),sep="") # gridded sensor zenith
|
64
|
tempfile2_path=paste(tempdir(),"/",bfile,".tif",sep="") #gridded/masked/processed path
|
65
|
outfile=paste("~/acrobates/adamw/projects/interp/data/modis/mod35/gridded/",bfile,".tif",sep="") #final file
|
66
|
if(file.exists(outfile)) return(c(file,0))
|
67
|
## get bounding coordinates
|
68
|
# glat=as.numeric(do.call(c,strsplit(sub("GRINGPOINTLATITUDE=","",system(paste("gdalinfo ",file," | grep GRINGPOINTLATITUDE"),intern=T)),split=",")))
|
69
|
# glon=as.numeric(do.call(c,strsplit(sub("GRINGPOINTLONGITUDE=","",system(paste("gdalinfo ",file," | grep GRINGPOINTLONGITUDE"),intern=T)),split=",")))
|
70
|
# bb=cbind(c(glon,glon[1]),c(glat,glat[1]))
|
71
|
# pp = SpatialPolygons(list(Polygons(list(Polygon(bb)),1)))
|
72
|
# proj4string(pp)=projection(glb)
|
73
|
# ppc=gIntersection(pp,gpp)
|
74
|
# ppc=gBuffer(ppc,width=0.3) #buffer a little to remove gaps between images
|
75
|
ppc=gpp
|
76
|
## First write the parameter file (careful, heg is very finicky!)
|
77
|
hdr=paste("NUM_RUNS = ",length(vars$varid),"|MULTI_BAND_HDFEOS:",length(vars$varid),sep="")
|
78
|
grp=paste("
|
79
|
BEGIN
|
80
|
INPUT_FILENAME=",file,"
|
81
|
OBJECT_NAME=mod35
|
82
|
FIELD_NAME=",vars$variable,"|
|
83
|
BAND_NUMBER = ",1:length(vars$varid),"
|
84
|
OUTPUT_PIXEL_SIZE_X=0.008333333
|
85
|
OUTPUT_PIXEL_SIZE_Y=0.008333333
|
86
|
SPATIAL_SUBSET_UL_CORNER = ( ",bbox(ppc)[2,2]," ",bbox(ppc)[1,1]," )
|
87
|
SPATIAL_SUBSET_LR_CORNER = ( ",bbox(ppc)[2,1]," ",bbox(ppc)[1,2]," )
|
88
|
OUTPUT_OBJECT_NAME = mod35|
|
89
|
RESAMPLING_TYPE =NN
|
90
|
OUTPUT_PROJECTION_TYPE = GEO
|
91
|
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 )
|
92
|
# 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 )
|
93
|
# projection parameters from http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/newPage.cgi?fileName=sn_gctp
|
94
|
ELLIPSOID_CODE = WGS84
|
95
|
OUTPUT_TYPE = HDFEOS
|
96
|
OUTPUT_FILENAME= ",tempfile_path,"
|
97
|
END
|
98
|
|
99
|
",sep="")
|
100
|
|
101
|
## if any remnants from previous runs remain, delete them
|
102
|
if(length(list.files(tempdir(),pattern=bfile)>0))
|
103
|
file.remove(list.files(tempdir(),pattern=bfile,full=T))
|
104
|
## write it to a file
|
105
|
cat( c(hdr,grp) , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
|
106
|
## now run the swath2grid tool
|
107
|
## write the gridded file
|
108
|
print(paste("Starting",file))
|
109
|
system(paste("(",stitch," -p ",tempdir(),"/",basename(file),"_MODparms.txt -d)",sep=""),intern=F)#,ignore.stderr=F)
|
110
|
############## Now run the 5km summary
|
111
|
## First write the parameter file (careful, heg is very finicky!)
|
112
|
hdr=paste("NUM_RUNS = ",nrow(vars[-1,]),"|MULTI_BAND_HDFEOS:",nrow(vars[-1,]),sep="")
|
113
|
grp=paste("
|
114
|
BEGIN
|
115
|
INPUT_FILENAME=",file,"
|
116
|
OBJECT_NAME=mod35
|
117
|
FIELD_NAME=",vars$variable[-1],"|
|
118
|
BAND_NUMBER = ",1,"
|
119
|
OUTPUT_PIXEL_SIZE_X=0.008333333
|
120
|
#0.0416666
|
121
|
OUTPUT_PIXEL_SIZE_Y=0.008333333
|
122
|
#0.0416666
|
123
|
SPATIAL_SUBSET_UL_CORNER = ( ",bbox(ppc)[2,2]," ",bbox(ppc)[1,1]," )
|
124
|
SPATIAL_SUBSET_LR_CORNER = ( ",bbox(ppc)[2,1]," ",bbox(ppc)[1,2]," )
|
125
|
#OUTPUT_OBJECT_NAME = mod35|
|
126
|
RESAMPLING_TYPE =NN
|
127
|
OUTPUT_PROJECTION_TYPE = GEO
|
128
|
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 )
|
129
|
#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 )
|
130
|
# projection parameters from http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/newPage.cgi?fileName=sn_gctp
|
131
|
ELLIPSOID_CODE = WGS84
|
132
|
OUTPUT_TYPE = HDFEOS
|
133
|
OUTPUT_FILENAME= ",tempfile_sz,"
|
134
|
END
|
135
|
|
136
|
",sep="")
|
137
|
|
138
|
## write it to a file
|
139
|
cat( c(hdr,grp) , file=paste(tempdir(),"/",basename(file),"_MODparms_angle.txt",sep=""))
|
140
|
|
141
|
## now run the swath2grid tool
|
142
|
## write the gridded file
|
143
|
print(paste("Starting",file))
|
144
|
system(paste("(",stitch," -p ",tempdir(),"/",basename(file),"_MODparms_angle.txt -d)",sep=""),intern=F,ignore.stderr=F)
|
145
|
####### import to R for processing
|
146
|
if(!file.exists(tempfile_path)) {
|
147
|
file.remove(list.files(tempdir(),pattern=bfile,full=T))
|
148
|
return(c(file,0))
|
149
|
}
|
150
|
## convert to land path
|
151
|
d=raster(paste("HDF4_EOS:EOS_GRID:\"",tempfile_path,"\":mod35:Cloud_Mask_0",sep=""))
|
152
|
sz=raster(paste("HDF4_EOS:EOS_GRID:\"",tempfile_sz,"\":mod35:Sensor_Zenith",sep=""))
|
153
|
NAvalue(sz)=0
|
154
|
## resample sensor angles to 1km grid and mask paths with angles >=30
|
155
|
# sz2=resample(sz,d,method="ngb",file=sub("hdf","tif",tempfile_sz),overwrite=T)
|
156
|
getlc=function(x,y) {ifelse(y==0|y>40,NA,((x%/%2^6) %% 2^2))}
|
157
|
path= overlay(d,sz,fun=getlc,filename=tempfile2_path,options=c("COMPRESS=LZW", "LEVEL=9","PREDICTOR=2"),datatype="INT1U",overwrite=T)
|
158
|
### warp them to align all pixels
|
159
|
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=""))
|
160
|
## delete temporary files
|
161
|
file.remove(list.files(tempdir(),pattern=bfile,full=T))
|
162
|
return(c(file,1))
|
163
|
}
|
164
|
|
165
|
|
166
|
## establish sudo priveleges to run swtif
|
167
|
system("sudo ls"); mclapply(files,getpath,mc.cores=10)
|
168
|
|
169
|
## check gdal can read all of them
|
170
|
gfiles=list.files("gridded",pattern="tif$",full=T)
|
171
|
length(gfiles)
|
172
|
|
173
|
check=do.call(rbind,mclapply(gfiles,function(file){
|
174
|
gd=system(paste("gdalinfo ",file,sep=""),intern=T)
|
175
|
if(any(grepl("Corner",gd))) return(1)
|
176
|
else return(0)
|
177
|
}))
|
178
|
|
179
|
table(check)
|
180
|
|
181
|
file.remove(gfiles[check==0])
|
182
|
|
183
|
## use new gdal
|
184
|
system(paste("/usr/local/gdal-1.10.0/bin/gdalwarp -wm 900 -overwrite -co COMPRESS=LZW -co PREDICTOR=2 -multi -r mode gridded/*.tif MOD35_path_gdalwarp.tif"))
|
185
|
|
186
|
|
187
|
### Merge them into a geotiff
|
188
|
system(paste("gdal_merge.py -v -init 255 -n 255 -o MOD35_ProcessPath_gdalmerge2.tif -co \"ZLEVEL=9\" -co \"COMPRESS=LZW\" -co \"PREDICTOR=2\" `ls -d -1 gridded/*.tif --sort=size `",sep=""))
|
189
|
|
190
|
# origin(raster(gfiles[5]))
|
191
|
|
192
|
## try with pktools
|
193
|
## global
|
194
|
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 &"))
|
195
|
#bb="-ulx -180 -uly 90 -lrx 180 -lry -90"
|
196
|
#bb="-ulx -180 -uly 90 -lrx 170 -lry 80"
|
197
|
bb="-ulx -72 -uly 11 -lrx -59 -lry -1"
|
198
|
|
199
|
|
200
|
#expand.grid(x=seq(-180,170,by=10),y=seq(-90,80))
|
201
|
gf2= grep("2012009[.]03",gfiles,value=T)
|
202
|
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"))
|
203
|
|
204
|
# bounding box?
|
205
|
|
206
|
###########
|
207
|
### Use GRASS to import all the tifs and calculat the mode
|
208
|
## make temporary working directory
|
209
|
tf=paste(tempdir(),"/grass", Sys.getpid(),"/", sep="") #temporar
|
210
|
if(!file.exists(tf)) dir.create(tf)
|
211
|
|
212
|
## set up temporary grass instance for this PID
|
213
|
gisBase="/usr/lib/grass64"
|
214
|
print(paste("Set up temporary grass session in",tf))
|
215
|
initGRASS(gisBase=gisBase,gisDbase=tf,SG=as(glb,"SpatialGridDataFrame"),override=T,location="mod35",mapset="PERMANENT",home=tf,pid=Sys.getpid())
|
216
|
system(paste("g.proj -c proj4=\"",projection(glb),"\"",sep=""),ignore.stdout=T,ignore.stderr=T)
|
217
|
|
218
|
## read in NPP grid to serve as grid
|
219
|
execGRASS("r.in.gdal",input=t@file@name,output="grid")
|
220
|
system("g.region rast=grid n=90 s=-90 save=roi --overwrite",ignore.stdout=F,ignore.stderr=F)
|
221
|
|
222
|
## get files already imported - only important if more tifs were written after an initial import
|
223
|
imported=basename(gfiles)%in%system("g.mlist type=rast pattern=MOD*",intern=T)
|
224
|
table(imported)
|
225
|
|
226
|
## read in all tifs
|
227
|
for(f in gfiles[!imported]) execGRASS("r.in.gdal",input=f,output=basename(f),flags="o")
|
228
|
|
229
|
## calculate mode
|
230
|
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"))
|
231
|
## add colors
|
232
|
execGRASS("r.colors",map="MOD35_path",rules="MOD35_path_grasscolors.txt")
|
233
|
## write to disk
|
234
|
execGRASS("r.out.gdal",input="MOD35_path",output=paste(getwd(),"/MOD35_ProcessPath_C5.tif",sep=""),type="Byte",createopt="COMPRESS=LZW,LEVEL=9,PREDICTOR=2")
|
235
|
|
236
|
### delete the temporary files
|
237
|
unlink_.gislock()
|
238
|
system(paste("rm -frR ",tf,sep=""))
|
239
|
|
240
|
#########################
|
241
|
|
242
|
|
243
|
cols=c("blue","lightblue","tan","green")
|
244
|
|
245
|
|
246
|
|
247
|
## connect to raster to extract land-cover bit
|
248
|
library(raster)
|
249
|
|
250
|
d=raster("CM.tif")
|
251
|
getlc=function(x) {(x/2^6) %% 2^2}
|
252
|
|
253
|
calc(d,fun=getlc,filename="CM_LC.tif")
|
254
|
|