Project

General

Profile

« Previous | Next » 

Revision 99b3508d

Added by Adam Wilson over 11 years ago

Added script to extract MOD35 processing path from swath level data and another to summarize MOD35 data. Also updated NDP-026D script to use new MOD35/09 summaries from Earth Engine

View differences:

climate/procedures/MOD35_Explore.r
4 4
library(raster)
5 5
library(rasterVis)
6 6
library(rgdal)
7
library(plotKML)
7 8

  
8 9
#f=list.files(pattern="*.hdf")
9 10

  
......
53 54
lulc2=aggregate(lulc,2,fun=function(x,na.rm=T) Mode(x))
54 55
## convert to factor table
55 56
lulcf=lulc2
56
ratify(lulcf)
57
levels(lulcf)[[1]]
58
lulc_levels=c("Water","Evergreen Needleleaf forest","Evergreen Broadleaf forest","Deciduous Needleleaf forest","Deciduous Broadleaf forest","Mixed forest","Closed shrublands","Open shrublands","Woody savannas","Savannas","Grasslands","Permanent wetlands","Croplands","Urban and built-up","Cropland/Natural vegetation mosaic","Snow and ice","Barren or sparsely vegetated")
59
lulc_levels2=c("Water","Forest","Forest","Forest","Forest","Forest","Shrublands","Shrublands","Savannas","Savannas","Grasslands","Permanent wetlands","Croplands","Urban and built-up","Cropland/Natural vegetation mosaic","Snow and ice","Barren or sparsely vegetated")
60

  
61
levels(lulcf)=list(data.frame(ID=0:16,LULC=lulc_levels,LULC2=lulc_levels2))
57
lulcf=ratify(lulcf)
58
levels(lulcf)
59
table(as.matrix(lulcf))
60
data(worldgrids_pal)  #load palette
61
IGBP=data.frame(ID=0:16,col=worldgrids_pal$IGBP[-c(18,19)],
62
  lulc_levels2=c("Water","Forest","Forest","Forest","Forest","Forest","Shrublands","Shrublands","Savannas","Savannas","Grasslands","Permanent wetlands","Croplands","Urban and built-up","Cropland/Natural vegetation mosaic","Snow and ice","Barren or sparsely vegetated"),stringsAsFactors=F)
63
IGBP$class=rownames(IGBP);rownames(IGBP)=1:nrow(IGBP)
64
levels(lulcf)=list(IGBP)
62 65

  
63 66

  
64 67
### load WORLDCLIM elevation 
......
84 87

  
85 88
## MOD17
86 89
mod17=raster("../MOD17/Npp_1km_C5.1_mean_00_to_06.tif",format="GTiff")
87
mod17=crop(projectRaster(mod17,v6,method="bilinear"),v6)
88 90
NAvalue(mod17)=32767
91
mod17=crop(projectRaster(mod17,v6,method="bilinear"),v6)
89 92

  
90 93
mod17qc=raster("../MOD17/Npp_QC_1km_C5.1_mean_00_to_06.tif",format="GTiff")
91 94
mod17qc=crop(projectRaster(mod17qc,v6,method="bilinear"),v6)
......
100 103
mod43qc[mod43qc<0|mod43qc>100]=NA
101 104

  
102 105
## Summary plot of mod17 and mod43
103
modprod=stack(mod17qc,mod43qc)
104
names(modprod)=c("MOD17","MOD43")
106
modprod=stack(mod17/cellStats(mod17,max)*100,mod17qc,mod43,mod43qc)
107
names(modprod)=c("MOD17","MOD17qc","MOD43","MOD43qc")
108

  
105 109

  
106 110
###
107 111

  
......
125 129
CairoPDF("output/mod35compare.pdf",width=11,height=8.5)
126 130
#CairoPNG("output/mod35compare_%d.png",units="in", width=11,height=8.5,pointsize=4000,dpi=1200,antialias="subpixel")
127 131

  
132
### LANDCOVER
133
levelplot(lulcf,col.regions=levels(lulcf)[[1]]$col,colorkey=list(space="right",at=0:16,labels=list(at=seq(0.5,16.5,by=1),labels=levels(lulcf)[[1]]$class,cex=2)),margin=F)
134

  
135

  
128 136
levelplot(mcompare,col.regions=cols,at=at,margin=F,sub="Frequency of MOD35 Clouds in March")
129 137
#levelplot(dif,col.regions=bgyr(20),margin=F)
130 138
levelplot(mdiff,col.regions=bgyr(100),at=seq(mdiff@data@min,mdiff@data@max,len=100),margin=F)
......
136 144
levelplot(modprod,main="Missing Data (%) in MOD17 (NPP) and MOD43 (BRDF Reflectance)",
137 145
          sub="Tile H11v08 (Venezuela)",col.regions=cols,at=at)
138 146

  
147

  
148

  
149

  
139 150
levelplot(modprod,main="Missing Data (%) in MOD17 (NPP) and MOD43 (BRDF Reflectance)",
140 151
          sub="Tile H11v08 (Venezuela)",col.regions=cols,at=at,
141 152
          xlim=c(-7300000,-6670000),ylim=c(0,600000))
climate/procedures/MOD35_ExtractProcessPath.r
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

  
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/Npp_1km_C5.1_mean_00_to_06.tif",sep=""))
22

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

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

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

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

  
38

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

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

  
43
files=paste(getwd(),"/",list.files("swath",pattern="hdf$",full=T),sep="")
44

  
45
## vars to process
46
vars=as.data.frame(matrix(c(
47
  "Cloud_Mask",              "CM",
48
#  "Quality_Assurance",       "QA"),
49
  byrow=T,ncol=2,dimnames=list(1:2,c("variable","varid"))),stringsAsFactors=F)
50

  
51
## establish sudo priveleges to run swtif
52
system("sudo ls")
53

  
54
mclapply(files,function(file){
55
  
56
  tempfile=paste(tempdir(),"/",basename(file),sep="")
57
#  tempfile2=paste("gridded/",sub("hdf","tif",basename(tempfile)),sep="")
58
  tempfile2=paste(tempdir(),"/",sub("hdf","tif",basename(tempfile)),sep="")
59

  
60
  outfile=paste("gridded2/",sub("hdf","tif",basename(tempfile)),sep="")
61

  
62
  if(file.exists(outfile)) return(c(file,0))
63
  ## First write the parameter file (careful, heg is very finicky!)
64
  hdr=paste("NUM_RUNS = ",length(vars$varid),"|MULTI_BAND_HDFEOS:",length(vars$varid),sep="")
65
  grp=paste("
66
BEGIN
67
INPUT_FILENAME=",file,"
68
OBJECT_NAME=mod35
69
FIELD_NAME=",vars$variable,"|
70
BAND_NUMBER = ",1:length(vars$varid),"
71
OUTPUT_PIXEL_SIZE_X=0.008333333
72
OUTPUT_PIXEL_SIZE_Y=0.008333333
73
SPATIAL_SUBSET_UL_CORNER = ( 90 -180 )
74
SPATIAL_SUBSET_LR_CORNER = ( -90 180 )
75
OUTPUT_OBJECT_NAME = mod35|
76
RESAMPLING_TYPE =NN
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= ",tempfile,"
84
END
85

  
86
",sep="")
87

  
88
  ## if any remnants from previous runs remain, delete them
89
   if(length(list.files(tempdir(),pattern=basename(file)))>0)
90
    file.remove(list.files(tempdir(),pattern=basename(file),full=T))
91
  ## write it to a file
92
 cat( c(hdr,grp)   , file=paste(tempdir(),"/",basename(file),"_MODparms.txt",sep=""))
93

  
94
  ## now run the swath2grid tool
95
  ## write the gridded file
96
  print(paste("Starting",file))
97
  system(paste("(",stitch," -p ",tempdir(),"/",basename(file),"_MODparms.txt -d ; echo $$)",sep=""),intern=T,ignore.stderr=F)
98
  ## convert to land path
99
  d=raster(paste("HDF4_EOS:EOS_GRID:\"",tempfile,"\":mod35:Cloud_Mask_0",sep=""))
100
#  za=raster(paste("HDF4_EOS:EOS_GRID:\"",tempfile,"\":mod35:Quality_Assurance_1",sep=""))
101
  ## add projection information - ellipsoid should be wgs84
102
  projection(d)=projection(glb)
103
  extent(d)=alignExtent(d,extent(glb))
104
                                        #  d=readAll(d)
105
  getlc=function(x) {(x%/%2^6) %% 2^2}
106
  calc(d,fun=getlc,filename=outfile,options=c("COMPRESS=LZW", "LEVEL=9","PREDICTOR=2"),datatype="INT1U",overwrite=T)
107

  
108
  ### warp it to align all pixels
109
  system(paste("gdalwarp -overwrite -tap -tr 0.008333333 0.008333333 -co COMPRESS=LZW -co LEVEL=9 -co PREDICTOR=2 -s_srs \"",projection(glb),"\" ",tempfile2," ",outfile,sep=""))
110

  
111
#  getqa=function(x) {(x%/%2^1) %% 2^3}
112
#  za=calc(za,fun=getqa)#,filename=outfile,options=c("COMPRESS=LZW", "LEVEL=9","PREDICTOR=2"),datatype="INT1U",overwrite=T)
113
  ## resample to line up with glb so we can use mosaic later
114
## delete temporary files
115
  file.remove(tempfile,tempfile2)
116
  return(c(file,1))
117
})
118

  
119
## check gdal can read all of them
120
gfiles=list.files("gridded",pattern="tif$",full=T)
121
length(gfiles)
122

  
123
check=do.call(rbind,mclapply(gfiles,function(file){
124
    gd=system(paste("gdalinfo ",file,sep=""),intern=T)
125
    if(any(grepl("Corner",gd))) return(1)
126
    else return(0)
127
}))
128

  
129
table(check)
130

  
131
file.remove(gfiles[check==0])
132

  
133
#  origin(raster(gfiles[5]))
134
  
135
  
136
  system(paste("gdalinfo ",gfiles[1]," | grep Origin"))
137
  system(paste("gdalinfo ",gfiles[2]," | grep Origin"))
138
  system(paste("gdalinfo ",gfiles[3]," | grep Origin"))
139

  
140
system(paste("gdalwarp -tap -tr 0.008333333 0.008333333 -s_srs \"",projection(glb),"\" ",gfiles[1]," test1.tif"))
141
system(paste("gdalwarp -tap -tr 0.008333333 0.008333333 -s_srs \"",projection(glb),"\" ",gfiles[2]," test2.tif"))
142
  system(paste("gdalinfo test1.tif | grep Origin"))
143
  system(paste("gdalinfo test2.tif | grep Origin"))
144
system(paste("pkmosaic ",paste("-i",gfiles[1:2],collapse=" ")," -o MOD35_path2.tif  -m 6 -v -t 255"))
145
system(paste("pkmosaic ",paste("-i",c("test1.tif","test2.tif"),collapse=" ")," -o MOD35_path2.tif  -m 6 -v -max 10 -ot Byte"))
146

  
147

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

  
155

  
156
#expand.grid(x=seq(-180,170,by=10),y=seq(-90,80))
157
  
158
system(paste("pkmosaic ",bb," -co COMPRESS=LZW -co PREDICTOR=2 ",paste("-i",list.files("gridded",full=T,pattern="tif$"),collapse=" ")," -o h11v08_path_pkmosaic.tif  -m 6 -v -t 255 -t 0 &"))
159

  
160
                                        #  bounding box?  
161

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

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

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

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

  
185
## calculate mode
186
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"))
187
## add colors
188
execGRASS("r.colors",map="MOD35_path",rules="MOD35_path_grasscolors.txt")
189
## write to disk
190
execGRASS("r.out.gdal",input="MOD35_path",output=paste(getwd(),"/MOD35_ProcessPath_C5.tif",sep=""),type="Byte",createopt="COMPRESS=LZW,LEVEL=9,PREDICTOR=2")
191

  
192
### delete the temporary files 
193
  unlink_.gislock()
194
  system(paste("rm -frR ",tf,sep=""))
195

  
196

  
197
#########################
198

  
199

  
200
cols=c("blue","lightblue","tan","green")
201

  
202

  
203
  ###  Merge them into a geotiff
204
    system(paste("gdal_merge.py -v -n 255 -o MOD35_ProcessPath.tif -co \"COMPRESS=LZW\" -co \"PREDICTOR=2\" `ls -d -1 gridded/*.tif`",sep=""))
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

  
climate/procedures/MOD35_Summary.r
1
### summarize MOD35 data
2
setwd("/home/adamw/acrobates/adamw/projects/interp/")
3

  
4
library(sp)
5
library(spgrass6)
6
library(rgdal)
7
library(reshape)
8
library(ncdf4)
9
library(geosphere)
10
library(rgeos)
11
library(multicore)
12
library(raster)
13
library(lattice)
14
library(rgl)
15
library(hdf5)
16
library(rasterVis)
17
library(heR.Misc)
18
library(car)
19

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

  
23
psin=CRS("+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs")
24

  
25
tile="h11v08"
26

  
27
## get MODLAND tile information
28
tb=read.table("http://landweb.nascom.nasa.gov/developers/sn_tiles/sn_bound_10deg.txt",skip=6,nrows=648,header=T)
29
tb$tile=paste("h",sprintf("%02d",tb$ih),"v",sprintf("%02d",tb$iv),sep="")
30
save(tb,file="modlandTiles.Rdata")
31

  
32
tile="h11v08"   #can move this to submit script if needed
33
#tile="h09v04"   #oregon
34

  
35
tile_bb=tb[tb$tile==tile,] ## identify tile of interest
36
roi_ll=extent(tile_bb$lon_min,tile_bb$lon_max,tile_bb$lat_min,tile_bb$lat_max) 
37
#roi=spTransform(roi,psin)
38
#roil=as(roi,"SpatialLines")
39

  
40
dmod06="data/modis/mod06/summary"
41
dmod35="data/modis/mod35/summary"
42

  
43

  
44

  
45

  
46
##################################################
47
### generate KML file for viewing in google earth
48
file=paste(dmod35,"/MOD35_",tile,"_ymonmean.nc",sep="")
49
m=1
50

  
51
cat("
52
0 green
53
50 grey 
54
90 blue
55
100 red
56
nv     0   0   0   0 
57
",file=paste(dmod35,"/mod35_colors.txt",sep=""))
58

  
59
system(paste("gdalinfo ",file,sep=""))
60

  
61
system(paste("gdalwarp -multi -r cubicspline -srcnodata 255 -dstnodata 255 -s_srs '+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs' -t_srs 'EPSG:4326' ",file, " MOD35_",tile,".tif",sep=""))
62
system(paste("gdaldem color-relief -b ",m," ",dmod35,"/MOD35_",tile,".tif mod35_colors.txt ",dmod35,"/MOD35_",tile,"_",m,".tif",sep=""))
63
system(paste("gdalinfo MOD35_",tile,"_",m,".tif",sep=""))
64

  
65
#system(paste("gdal_translate -b ",m," MOD35_",tile,".tif MOD35_",tile,"_",m,".tif",sep=""))
66
40075=256*(2^z))  #find zoom level
67

  
68
system(paste("gdal2tiles.py -z 1-8 -k ",dmod35,"/MOD35_",tile,"_",m,".tif",sep=""))
69

  
70
### Wind Direction
71
winddir="home/adamw/acrobates/adamw/projects/interp/data/ncep/"
72
dir.create(winddir)
73
system(paste("wget ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.derived/surface/vwnd.mon.ltm.nc -P ",winddir))
climate/procedures/NDP-026D.R
70 70
             cldsd=sd(x$Amt[x$Nobs>10]/100,na.rm=T))}))
71 71
cldm[,c("lat","lon")]=st[match(cldm$StaID,st$StaID),c("lat","lon")]
72 72

  
73
## means by year
74
cldy=do.call(rbind.data.frame,by(cld,list(year=as.factor(cld$YR),StaID=as.factor(cld$StaID)),function(x){
75
  data.frame(
76
             year=x$YR[1],
77
             StaID=x$StaID[1],
78
             cld=mean(x$Amt[x$Nobs>10]/100,na.rm=T),
79
             cldsd=sd(x$Amt[x$Nobs>10]/100,na.rm=T))}))
80
cldy[,c("lat","lon")]=st[match(cldy$StaID,st$StaID),c("lat","lon")]
81

  
82

  
73 83
#cldm=foreach(m=unique(cld$month),.combine='rbind')%:%
74 84
#  foreach(s=unique(cld$StaID),.combine="rbind") %dopar% {
75 85
#    x=cld[cld$month==m&cld$StaID==s,]
......
79 89
#               Amt=mean(x$Amt[x$Nobs>10],na.rm=T)/100)}
80 90
 
81 91

  
82
## write out the table
92
## write out the tables
93
write.csv(cldy,file="cldy.csv")
83 94
write.csv(cldm,file="cldm.csv")
84 95

  
85 96

  
86 97
##################
87 98
###
88 99
cldm=read.csv("cldm.csv")
100
cldy=read.csv("cldy.csv")
89 101

  
90 102

  
91 103
##make spatial object
......
96 108
#### Evaluate MOD35 Cloud data
97 109
mod35=brick("../modis/mod35/MOD35_h11v08.nc",varname="CLD01")
98 110
mod35sd=brick("../modis/mod35/MOD35_h11v08.nc",varname="CLD_sd")
99

  
100 111
projection(mod35)="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs"
101
projection(mod35sd)="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs"
112

  
113

  
114
### use data from google earth engine
115
mod35=brick("../modis/mod09/global_2009/")
116
mod09=raster("../modis/mod09/global_2009/MOD09_2009.tif")
117

  
118
n=100
119
at=seq(0,100,length=n)
120
colr=colorRampPalette(c("black","green","red"))
121
cols=colr(n)
122

  
123
levelplot(mod09,col.regions=cols,at=at)
124

  
102 125

  
103 126
cldms=spTransform(cldms,CRS(projection(mod35)))
104 127

  

Also available in: Unified diff