Project

General

Profile

Download (25.6 KB) Statistics
| Branch: | Revision:
1 ddd9a810 Adam M. Wilson
## Figures associated with MOD35 Cloud Mask Exploration
2
3
setwd("~/acrobates/adamw/projects/MOD35C5")
4
5
library(raster);beginCluster(10)
6
library(rasterVis)
7
library(rgdal)
8
library(plotKML)
9
library(Cairo)
10
library(reshape)
11 be7b1081 Adam M. Wilson
library(rgeos)
12 14ad4a96 Adam M. Wilson
library(splancs)
13 ddd9a810 Adam M. Wilson
14 58d05081 Adam M. Wilson
15
## add tags for distribution
16
## MOD35
17
tags=c("TIFFTAG_IMAGEDESCRIPTION='Collection 5 MOD35 Cloud Frequency for 2009 extracted from MOD09GA state_1km bits 0-1. The MOD35 bits encode four categories (with associated confidence that the pixel is actually clear): confidently clear (confidence > 0.99), probably clear (0.99 >= confidence > 0.95), probably cloudy (0.95 >= confidence > 0.66), and confidently cloudy (confidence <= 0.66).  Following the advice of the MODIS science team (Frey, 2010), we binned confidently clear and probably clear together as clear and the other two classes as cloudy.  The daily cloud mask time series were summarized to mean cloud frequency (CF) by calculating the proportion of cloudy days during 2009'",
18
  "TIFFTAG_DOCUMENTNAME='Collection 5 MOD35 Cloud Frequency'",
19
  "TIFFTAG_DATETIME='20090101'",
20
  "TIFFTAG_ARTIST='Adam M. Wilson (adam.wilson@yale.edu)'")
21
system(paste("/usr/local/src/gdal-1.10.0/swig/python/scripts/gdal_edit.py data/MOD35_2009.tif ",paste("-mo ",tags,sep="",collapse=" "),sep=""))
22
## MOD09
23
tags=c("TIFFTAG_IMAGEDESCRIPTION='Collection 5 MOD09 Cloud Frequency for 2009 extracted from MOD09GA \'PGE11\' internal cloud mask algorithm (embedded in MOD09GA \'state_1km\' bit 10. The daily cloud mask time series were summarized to mean cloud frequency (CF) by calculating the proportion of cloudy days during 2009'",
24
  "TIFFTAG_DOCUMENTNAME='Collection 5 MOD09 Cloud Frequency'",
25
  "TIFFTAG_DATETIME='20090101'",
26
  "TIFFTAG_ARTIST='Adam M. Wilson (adam.wilson@yale.edu)'")
27
system(paste("/usr/local/src/gdal-1.10.0/swig/python/scripts/gdal_edit.py data/MOD09_2009.tif ",paste("-mo ",tags,sep="",collapse=" "),sep=""))
28
29 be7b1081 Adam M. Wilson
## get % cloudy
30
mod09=raster("data/MOD09_2009.tif")
31 d39ab57e Adam M. Wilson
names(mod09)="C5MOD09CF"
32 be7b1081 Adam M. Wilson
NAvalue(mod09)=0
33
34
mod35c5=raster("data/MOD35_2009.tif")
35
names(mod35c5)="C5MOD35CF"
36
NAvalue(mod35c5)=0
37
38 58d05081 Adam M. Wilson
39 be7b1081 Adam M. Wilson
## mod35C6 annual
40 a57c4e3d Adam M. Wilson
if(!file.exists("data/MOD35C6_2009.tif")){
41 84d4d760 Adam M. Wilson
  system("/usr/local/gdal-1.10.0/bin/gdalbuildvrt  -a_srs '+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs' -sd 1 -b 1 data/MOD35C6.vrt `find /home/adamw/acrobates/adamw/projects/interp/data/modis/mod35/summary/ -name '*h[1-9]*_mean.nc'` ")
42 598244e1 Adam M. Wilson
  system("align.sh data/MOD35C6.vrt data/MOD09_2009.tif data/MOD35C6_2009.tif")
43 a57c4e3d Adam M. Wilson
}
44 58d05081 Adam M. Wilson
45 57d44dd9 Adam M. Wilson
mod35c6=raster("data/MOD35C6_2009.tif")
46 be7b1081 Adam M. Wilson
names(mod35c6)="C6MOD35CF"
47
NAvalue(mod35c6)=255
48
49 a57c4e3d Adam M. Wilson
## landcover
50 5f212fe8 Adam M. Wilson
if(!file.exists("data/MCD12Q1_IGBP_2009_051_wgs84_1km.tif")){
51 a57c4e3d Adam M. Wilson
  system(paste("/usr/local/gdal-1.10.0/bin/gdalwarp -tr 0.008983153 0.008983153 -r mode -ot Byte -co \"COMPRESS=LZW\"",
52 d39ab57e Adam M. Wilson
               " /mnt/data/jetzlab/Data/environ/global/MODIS/MCD12Q1/051/MCD12Q1_051_2009_wgs84.tif ",
53 a57c4e3d Adam M. Wilson
               " -t_srs \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\" ",
54 5f212fe8 Adam M. Wilson
               " -te -180.0044166 -60.0074610 180.0044166 90.0022083 ",
55
               "data/MCD12Q1_IGBP_2009_051_wgs84_1km.tif -overwrite ",sep=""))}
56
lulc=raster("data/MCD12Q1_IGBP_2009_051_wgs84_1km.tif")
57 a57c4e3d Adam M. Wilson
58
  data(worldgrids_pal)  #load palette
59
  IGBP=data.frame(ID=0:16,col=worldgrids_pal$IGBP[-c(18,19)],
60
    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)
61
  IGBP$class=rownames(IGBP);rownames(IGBP)=1:nrow(IGBP)
62
  levels(lulc)=list(IGBP)
63
names(lulc)="MCD12Q1"
64
65
## make land mask
66
if(!file.exists("data/land.tif"))
67
  land=calc(lulc,function(x) ifelse(x==0,NA,1),file="data/land.tif",options=c("COMPRESS=LZW","ZLEVEL=9","PREDICTOR=2"),datatype="INT1U",overwrite=T)
68
land=raster("data/land.tif")
69
70 ddd9a810 Adam M. Wilson
#####################################
71
### compare MOD43 and MOD17 products
72
73
## MOD17
74 a57c4e3d Adam M. Wilson
if(!file.exists("data/MOD17.tif"))
75
system("align.sh ~/acrobates/adamw/projects/interp/data/modis/MOD17/MOD17A3_Science_NPP_mean_00_12.tif data/MOD09_2009.tif data/MOD17.tif")
76
mod17=raster("data/MOD17.tif",format="GTiff")
77
NAvalue(mod17)=65535
78 d39ab57e Adam M. Wilson
names(mod17)="MOD17_unscaled"
79 ddd9a810 Adam M. Wilson
80 a57c4e3d Adam M. Wilson
if(!file.exists("data/MOD17qc.tif"))
81
  system("align.sh ~/acrobates/adamw/projects/interp/data/modis/MOD17/MOD17A3_Science_NPP_Qc_mean_00_12.tif data/MOD09_2009.tif data/MOD17qc.tif")
82
mod17qc=raster("data/MOD17qc.tif",format="GTiff")
83 ddd9a810 Adam M. Wilson
NAvalue(mod17qc)=255
84 be7b1081 Adam M. Wilson
names(mod17qc)="MOD17CF"
85 ddd9a810 Adam M. Wilson
86
## MOD11 via earth engine
87 a57c4e3d Adam M. Wilson
if(!file.exists("data/MOD11_2009.tif"))
88
  system("align.sh ~/acrobates/adamw/projects/interp/data/modis/mod11/2009/MOD11_LST_2009.tif data/MOD09_2009.tif data/MOD11_2009.tif")
89
mod11=raster("data/MOD11_2009.tif",format="GTiff")
90 d39ab57e Adam M. Wilson
names(mod11)="MOD11_unscaled"
91 be7b1081 Adam M. Wilson
NAvalue(mod11)=0
92 a57c4e3d Adam M. Wilson
if(!file.exists("data/MOD11qc_2009.tif"))
93
  system("align.sh ~/acrobates/adamw/projects/interp/data/modis/mod11/2009/MOD11_Pmiss_2009.tif data/MOD09_2009.tif data/MOD11qc_2009.tif")
94
mod11qc=raster("data/MOD11qc_2009.tif",format="GTiff")
95 be7b1081 Adam M. Wilson
names(mod11qc)="MOD11CF"
96 ddd9a810 Adam M. Wilson
97
### Processing path
98 a57c4e3d Adam M. Wilson
if(!file.exists("data/MOD35pp.tif"))
99 57d44dd9 Adam M. Wilson
system("align.sh data/C5MOD35_ProcessPath.tif data/MOD09_2009.tif data/MOD35pp.tif")
100 a57c4e3d Adam M. Wilson
pp=raster("data/MOD35pp.tif")
101 be7b1081 Adam M. Wilson
NAvalue(pp)=255
102
names(pp)="MOD35pp"
103 ddd9a810 Adam M. Wilson
104
105
###
106
n=100
107
at=seq(0,100,len=n)
108
cols=grey(seq(0,1,len=n))
109
cols=rainbow(n)
110
bgyr=colorRampPalette(c("blue","green","yellow","red"))
111
cols=bgyr(n)
112
113
### Transects
114
r1=Lines(list(
115
  Line(matrix(c(
116 be7b1081 Adam M. Wilson
                -61.688,4.098,
117
                -59.251,3.430
118 ddd9a810 Adam M. Wilson
                ),ncol=2,byrow=T))),"Venezuela")
119
r2=Lines(list(
120
  Line(matrix(c(
121
                133.746,-31.834,
122
                134.226,-32.143
123
                ),ncol=2,byrow=T))),"Australia")
124
r3=Lines(list(
125
  Line(matrix(c(
126
                73.943,27.419,
127
                74.369,26.877
128
                ),ncol=2,byrow=T))),"India")
129 57d44dd9 Adam M. Wilson
r4=Lines(list(
130 ddd9a810 Adam M. Wilson
  Line(matrix(c(
131 be7b1081 Adam M. Wilson
                33.195,12.512,
132
                33.802,12.894
133
                ),ncol=2,byrow=T))),"Sudan")
134
135
136
137 57d44dd9 Adam M. Wilson
trans=SpatialLines(list(r1,r2,r3,r4),CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "))
138 be7b1081 Adam M. Wilson
### write out shapefiles of transects
139
writeOGR(SpatialLinesDataFrame(trans,data=data.frame(ID=names(trans)),match.ID=F),"output",layer="transects",driver="ESRI Shapefile",overwrite=T)
140
141
## buffer transects to get regional values 
142 14ad4a96 Adam M. Wilson
transb=gBuffer(trans,byid=T,width=0.4)
143 be7b1081 Adam M. Wilson
144
## make polygons of bounding boxes
145
bb0 <- lapply(slot(transb, "polygons"), bbox)
146
bb1 <- lapply(bb0, bboxx)
147
# turn these into matrices using a helper function in splancs
148
bb2 <- lapply(bb1, function(x) rbind(x, x[1,]))
149
# close the matrix rings by appending the first coordinate
150
rn <- row.names(transb)
151
# get the IDs
152
bb3 <- vector(mode="list", length=length(bb2))
153
# make somewhere to keep the output
154
for (i in seq(along=bb3)) bb3[[i]] <- Polygons(list(Polygon(bb2[[i]])),
155
                   ID=rn[i])
156
# loop over the closed matrix rings, adding the IDs
157
bbs <- SpatialPolygons(bb3, proj4string=CRS(proj4string(transb)))
158
159
trd1=lapply(1:length(transb),function(x) {
160
  td=crop(mod11,transb[x])
161
  tdd=lapply(list(mod35c5,mod35c6,mod09,mod17,mod17qc,mod11,mod11qc,lulc,pp),function(l) resample(crop(l,transb[x]),td,method="ngb"))
162
  ## normalize MOD11 and MOD17
163 d39ab57e Adam M. Wilson
  for(j in which(do.call(c,lapply(tdd,function(i) names(i)))%in%c("MOD11_unscaled","MOD17_unscaled"))){
164 be7b1081 Adam M. Wilson
    trange=cellStats(tdd[[j]],range)
165 5f212fe8 Adam M. Wilson
    tscaled=100*(tdd[[j]]-trange[1])/(trange[2]-trange[1])
166
    tscaled@history=list(range=trange)
167 d39ab57e Adam M. Wilson
    names(tscaled)=sub("_unscaled","",names(tdd[[j]]))
168 5f212fe8 Adam M. Wilson
    tdd=c(tdd,tscaled)
169 be7b1081 Adam M. Wilson
  }
170
  return(brick(tdd))
171
})
172
173
## bind all subregions into single dataframe for plotting
174
trd=do.call(rbind.data.frame,lapply(1:length(trd1),function(i){
175
  d=as.data.frame(as.matrix(trd1[[i]]))
176
  d[,c("x","y")]=coordinates(trd1[[i]])
177
  d$trans=names(trans)[i]
178
  d=melt(d,id.vars=c("trans","x","y"))
179
  return(d)
180
}))
181
182
transd=do.call(rbind.data.frame,lapply(1:length(trans),function(l) {
183
  td=as.data.frame(extract(trd1[[l]],trans[l],along=T,cellnumbers=F)[[1]])
184
  td$loc=extract(trd1[[l]],trans[l],along=T,cellnumbers=T)[[1]][,1]
185
  td[,c("x","y")]=xyFromCell(trd1[[l]],td$loc)
186
  td$dist=spDistsN1(as.matrix(td[,c("x","y")]), as.matrix(td[1,c("x","y")]),longlat=T)
187
  td$transect=names(trans[l])
188
  td2=melt(td,id.vars=c("loc","x","y","dist","transect"))
189
  td2=td2[order(td2$variable,td2$dist),]
190
  # get per variable ranges to normalize
191
  tr=cast(melt.list(tapply(td2$value,td2$variable,function(x) data.frame(min=min(x,na.rm=T),max=max(x,na.rm=T)))),L1~variable)
192
  td2$min=tr$min[match(td2$variable,tr$L1)]
193
  td2$max=tr$max[match(td2$variable,tr$L1)]
194
  print(paste("Finished ",names(trans[l])))
195 ddd9a810 Adam M. Wilson
  return(td2)}
196 be7b1081 Adam M. Wilson
  ))
197
198
transd$type=ifelse(grepl("MOD35|MOD09|CF",transd$variable),"CF","Data")
199
200 5f212fe8 Adam M. Wilson
201
## comparison of % cloudy days
202 d39ab57e Adam M. Wilson
if(!file.exists("data/dif_c5_09.tif"))
203
  overlay(mod35c5,mod09,fun=function(x,y) {return(x-y)},file="data/dif_c5_09.tif",format="GTiff",options=c("COMPRESS=LZW","ZLEVEL=9"),overwrite=T)
204
dif_c5_09=raster("data/dif_c5_09.tif",format="GTiff")
205
206 5f212fe8 Adam M. Wilson
207 84d4d760 Adam M. Wilson
##################################################################################
208
## Identify problematic areas with hard edges in cloud frequency
209 57d44dd9 Adam M. Wilson
############################
210 84d4d760 Adam M. Wilson
library(multicore)
211
212
## set up processing chunks
213 57d44dd9 Adam M. Wilson
nrw=nrow(mod35c5)
214
nby=10
215
nrwg=seq(1,nrw,by=nby)
216 84d4d760 Adam M. Wilson
writeLines(paste("Processing ",length(nrwg)," groups and",nrw,"lines"))
217 57d44dd9 Adam M. Wilson
218 84d4d760 Adam M. Wilson
## Parallel loop to conduct moving window analysis and quantify pixels with significant shifts across pp or lulc boundaries
219 57d44dd9 Adam M. Wilson
output=mclapply(nrwg,function(ti){
220
  ## Extract focal areas 
221
  ngb=5
222
  vals=getValuesFocal(mod35c5,ngb=ngb,row=ti,nrows=nby)
223 84d4d760 Adam M. Wilson
  vals_mod09=getValuesFocal(mod09,ngb=ngb,row=ti,nrows=nby)
224 57d44dd9 Adam M. Wilson
  pp_ind=getValuesFocal(pp,ngb=ngb,row=ti,nrows=nby)
225
  lulc_ind=getValuesFocal(lulc,ngb=ngb,row=ti,nrows=nby)
226
  ## processing path
227
  pp_bias=raster(matrix(do.call(rbind,lapply(1:nrow(vals),function(i) {
228
    tind1=pp_ind[i,]  #vector of indices
229
    tval1=vals[i,]    # vector of values
230
    tind2=tind1[!is.na(tind1)&!is.na(tval1)]  #which classes exist without NAs?
231
    if(length(unique(tind2))<2) return(255)  #if only one class, return 255
232
    if(sort(table(tind2),dec=T)[2]<5) return(254) # if too few observations of class 2, return 254
233 fe4c013a Adam M. Wilson
#    return(round(kruskal.test(tval1,tind1)$p.value*100))         # if it works, return p.value*100
234
    m=mean(tval1,na.rm=T)
235
    dif=round(diff(range(tapply(tval1,tind1,mean)))/m*100)
236
    return(dif)         # if it works, return p.value*100
237 57d44dd9 Adam M. Wilson
  })),nrow=nby,ncol=ncol(mod35c5),byrow=T))     # turn it back into a raster
238 fe4c013a Adam M. Wilson
  ## update raster and write it
239 57d44dd9 Adam M. Wilson
  extent(pp_bias)=extent(mod35c5[ti:(ti+nby-1),1:ncol(mod35c5),drop=F])
240
  projection(pp_bias)=projection(mod35c5)
241 84d4d760 Adam M. Wilson
  NAvalue(pp_bias) <- 255
242 57d44dd9 Adam M. Wilson
  writeRaster(pp_bias,file=paste("data/tiles/pp_bias_",ti,".tif",sep=""),
243
              format="GTiff",dataType="INT1U",overwrite=T,NAflag=255) #,options=c("COMPRESS=LZW","ZLEVEL=9")
244
  ## landcover
245
  lulc_bias=raster(matrix(do.call(rbind,lapply(1:nrow(vals),function(i) {
246
    tind1=lulc_ind[i,]  #vector of indices
247
    tval1=vals[i,]    # vector of values
248
    tind2=tind1[!is.na(tind1)&!is.na(tval1)]  #which classes exist without NAs?
249
    if(length(unique(tind2))<2) return(255)  #if only one class, return 255
250
    if(sort(table(tind2),dec=T)[2]<5) return(254) # if too few observations of class 2, return 254
251 fe4c013a Adam M. Wilson
#    return(round(kruskal.test(tval1,tind1)$p.value*100))         # if it works, get p.value*100
252
    m=mean(tval1,na.rm=T)
253
    dif=round(diff(range(tapply(tval1,tind1,mean)))/m*100)
254
    return(dif)         # if it works, return the normalized difference
255 57d44dd9 Adam M. Wilson
  })),nrow=nby,ncol=ncol(mod35c5),byrow=T))     # turn it back into a raster
256
  ## udpate raster and write it
257
  extent(lulc_bias)=extent(mod35c5[ti:(ti+nby-1),1:ncol(mod35c5),drop=F])
258
  projection(lulc_bias)=projection(mod35c5)
259 84d4d760 Adam M. Wilson
  NAvalue(lulc_bias) <- 255
260 57d44dd9 Adam M. Wilson
  writeRaster(lulc_bias,file=paste("data/tiles/lulc_bias_",ti,".tif",sep=""),
261 84d4d760 Adam M. Wilson
              format="GTiff",dataType="INT1U",overwrite=T,NAflag=255)#,options=c("COMPRESS=LZW","ZLEVEL=9")
262
263
    ## MOD09
264
  mod09_lulc_bias=raster(matrix(do.call(rbind,lapply(1:nrow(vals_mod09),function(i) {
265
    tind1=lulc_ind[i,]  #vector of indices
266
    tval1=vals_mod09[i,]    # vector of values
267
    tind2=tind1[!is.na(tind1)&!is.na(tval1)]  #which classes exist without NAs?
268
    if(length(unique(tind2))<2) return(255)  #if only one class, return 255
269
    if(sort(table(tind2),dec=T)[2]<5) return(254) # if too few observations of class 2, return 254
270 fe4c013a Adam M. Wilson
#    return(round(kruskal.test(tval1,tind1)$p.value*100))         # if it works, get p.value*100
271
    m=mean(tval1,na.rm=T)
272
    dif=round(diff(range(tapply(tval1,tind1,mean)))/m*100)
273
    return(dif)         # if it works, return normalized difference
274 84d4d760 Adam M. Wilson
  })),nrow=nby,ncol=ncol(mod35c5),byrow=T))     # turn it back into a raster
275
  ## udpate raster and write it
276
  extent(mod09_lulc_bias)=extent(mod09[ti:(ti+nby-1),1:ncol(mod09),drop=F])
277
  projection(mod09_lulc_bias)=projection(mod09)
278
  NAvalue(mod09_lulc_bias) <- 255
279
  writeRaster(mod09_lulc_bias,file=paste("data/tiles/mod09_lulc_bias_",ti,".tif",sep=""),
280
              format="GTiff",dataType="INT1U",overwrite=T,NAflag=255)#,options=c("COMPRESS=LZW","ZLEVEL=9")
281
282 57d44dd9 Adam M. Wilson
  return(ti)
283 84d4d760 Adam M. Wilson
},mc.cores=15)
284 57d44dd9 Adam M. Wilson
285
286
### check raster temporary files
287
showTmpFiles()
288
#removeTmpFiles(h=1)
289
290
## merge all the files back again
291 84d4d760 Adam M. Wilson
  system("gdalbuildvrt -srcnodata 255 -vrtnodata 255 data/lulc_bias.vrt `find data/tiles -name 'lulc_bias*tif'` ")
292
  system("gdalwarp -srcnodata 255 -dstnodata 255 -multi -r bilinear -co 'COMPRESS=LZW' -co 'ZLEVEL=9' data/lulc_bias.vrt data/lulc_bias.tif -r near")
293
#  system("align.sh data/lulc_bias.vrt data/MOD09_2009.tif data/lulc_bias.tif")
294 57d44dd9 Adam M. Wilson
295
  system("gdalbuildvrt data/pp_bias.vrt `find data/tiles -name 'pp_bias*tif'` ")
296 84d4d760 Adam M. Wilson
  system("gdalwarp -srcnodata 255 -dstnodata 255 -multi -r bilinear -co 'COMPRESS=LZW' -co 'ZLEVEL=9' data/pp_bias.vrt data/pp_bias.tif -r near")
297
  system("align.sh -srcnodata 255 -dstnodata 255 -multi -r bilinear data/pp_bias.vrt data/MOD09_2009.tif data/pp_bias_align.tif &")
298 57d44dd9 Adam M. Wilson
299 84d4d760 Adam M. Wilson
  system("gdalbuildvrt data/mod09_lulc_bias.vrt `find data/tiles -name 'mod09_lulc_bias*tif'` ")
300
  system("gdalwarp -srcnodata 255 -dstnodata 255 -multi -r bilinear -co 'COMPRESS=LZW' -co 'ZLEVEL=9' data/mod09_lulc_bias.vrt data/mod09_lulc_bias.tif -r near")
301 57d44dd9 Adam M. Wilson
302 84d4d760 Adam M. Wilson
### read them back in
303
pp_bias=raster("data/pp_bias.tif")
304
names(pp_bias)="Processing Path"
305 58d05081 Adam M. Wilson
NAvalue(pp_bias)=255
306 84d4d760 Adam M. Wilson
lulc_bias=raster("data/lulc_bias.tif")
307
names(lulc_bias)="Land Use Land Cover"
308 58d05081 Adam M. Wilson
NAvalue(lulc_bias)=255
309
310
## read in WWF biome data to summarize by biome
311
if(!file.exists("data/teow/wwf_terr_ecos.shp"){
312
  system("wget -O data/teow.zip http://assets.worldwildlife.org/publications/15/files/original/official_teow.zip?1349272619")
313
  system("unzip data/teow.zip -d data/teow/")
314
   biome=readOGR("data/teow/wwf_terr_ecos.shp","wwf_terr_ecos")
315
   biome=biome[biome$BIOME<50,]
316
   biome2=gUnaryUnion(biome,id=biome$BIOME)
317
  ## create biome.csv using names in html file   
318
  biomeid=read.csv("data/teow/biome.csv",stringsAsFactors=F)
319
  biome2=SpatialPolygonsDataFrame(biome2,data=biomeid)
320
  writeOGR(biome2,"data/teow","biomes",driver="ESRI Shapefile")
321
}
322
   biome=readOGR("data/teow/biomes.shp","biomes")
323
324
biome2=extract(pp_bias,biome[biome$Biome==12,],df=T,fun=function(x) data.frame(mean=mean(x,na.rm=T),sd=sd(x,na.rm=T),prop=(sum(!is.na(x))/length(x))))
325 84d4d760 Adam M. Wilson
326 58d05081 Adam M. Wilson
pat=c(seq(0,100,len=100),254)#seq(0,0.-5,len=2) #,seq(0.05,.1,len=50))
327
grayr2=colorRampPalette(c("grey","green","red"))#
328
#grayr2=colorRampPalette(grey(c(.75,.5,.25)))
329 84d4d760 Adam M. Wilson
levelplot(stack(pp_bias,lulc_bias),col.regions=c(grayr2(2)),at=pat,
330
          colorkey=F,margin=F,maxpixels=1e6)+layer(sp.lines(coast,lwd=.5))
331 58d05081 Adam M. Wilson
levelplot(lulc_bias,col.regions=c(grayr2(100),"black"),at=pat,
332
          colorkey=T,margin=F,maxpixels=1e4)+layer(sp.lines(coast,lwd=.5))
333
334
histogram(lulc_bias)
335 57d44dd9 Adam M. Wilson
336
cor(td1$MOD17,td1$C6MOD35,use="complete",method="spearman")
337
cor(td1$MOD17[td1$edgeb==1],td1$C5MOD35[td1$edgeb==1],use="complete",method="spearman")
338
339
bwplot(value~MOD35pp|variable,data=td1l[td1l$pedgeb==1,],horizontal=F)
340
341 84d4d760 Adam M. Wilson
crosstab(dif_c5_09,pp)
342 d39ab57e Adam M. Wilson
### Correlations
343
#trdw=cast(trd,trans+x+y~variable,value="value")
344
#cor(trdw$MOD17,trdw$C5MOD35,use="complete",method="spearman")
345 5f212fe8 Adam M. Wilson
346 d39ab57e Adam M. Wilson
#Across all pixels in the four regions analyzed in Figure 3 there is a much larger correlation between mean NPP and the C5 MOD35 CF (Spearman’s ρ = -0.61, n=58,756) than the C6 MOD35 CF (ρ = 0.00, n=58,756) or MOD09 (ρ = -0.07, n=58,756) products.  
347
#by(trdw,trdw$trans,function(x) cor(as.data.frame(na.omit(x[,c("C5MOD35CF","C6MOD35CF","C5MOD09CF","MOD17","MOD11")])),use="complete",method="spearman"))
348 598244e1 Adam M. Wilson
349
350 d39ab57e Adam M. Wilson
## table of correlations
351
#trdw_cor=as.data.frame(na.omit(trdw[,c("C5MOD35CF","C6MOD35CF","C5MOD09CF","MOD17","MOD11")]))
352
#nrow(trdw_cor)
353
#round(cor(trdw_cor,method="spearman"),2)
354 5f212fe8 Adam M. Wilson
355 be7b1081 Adam M. Wilson
356 d39ab57e Adam M. Wilson
## set up some graphing parameters
357 be7b1081 Adam M. Wilson
at=seq(0,100,leng=100)
358
bgyr=colorRampPalette(c("purple","blue","green","yellow","orange","red","red"))
359 57d44dd9 Adam M. Wilson
bgray=colorRampPalette(c("purple","blue","deepskyblue4"))
360
grayr=colorRampPalette(c("grey","red","darkred"))
361
bgrayr=colorRampPalette(c("darkblue","blue","grey","red","purple"))
362
363 be7b1081 Adam M. Wilson
cols=bgyr(100)
364
365 57d44dd9 Adam M. Wilson
strip=strip.custom(par.strip.text=list(cex=.7),bg="transparent")
366
367 be7b1081 Adam M. Wilson
## global map
368
library(maptools)
369
coast=map2SpatialLines(map("world", interior=FALSE, plot=FALSE),proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
370
371 57d44dd9 Adam M. Wilson
g1=levelplot(stack(mod35c5,mod35c6,mod09),xlab=" ",scales=list(x=list(draw=F),y=list(alternating=1)),
372
  col.regions=cols,at=at,cuts=length(at),maxpixels=1e6,
373
  colorkey=list(at=at))+
374
#  layer(sp.polygons(bbs,lwd=5,col="black"))+
375
  layer(sp.lines(coast,lwd=.5))+
376
  layer(sp.points(coordinates(bbs),col="black",cex=2,pch=13,lwd=2))
377
378
### Plot of differences between MOD09 adn MOD35 masks
379
#system("gdalinfo -stats /home/adamw/acrobates/adamw/projects/MOD35C5/data/dif_c5_09.tif")
380
## get quantiles for color bar of differences
381
#qs=unique(quantile(as.vector(as.matrix(dif_c5_09)),seq(0,1,len=100),na.rm=T))
382
#c(bgray(sum(qs<0)),grayr(sum(qs>=0)+1))
383
qs=seq(-80,80,len=100)
384
g2=levelplot(dif_c5_09,col.regions=bgrayr(100),cuts=100,at=qs,margin=F,ylab=" ",colorkey=list("right",at=qs),maxpixels=1e6)+
385
  layer(sp.points(coordinates(bbs),col="black",cex=2,pch=13,lwd=2))+
386
  #layer(sp.polygons(bbs,lwd=2))+
387
  layer(sp.lines(coast,lwd=.5))
388 598244e1 Adam M. Wilson
389 d39ab57e Adam M. Wilson
g2$strip=strip.custom(var.name="Difference (C5MOD35-C5MOD09)",style=1,strip.names=T,strip.levels=F)  #update strip text
390
#g3=histogram(dif_c5_09,col="black",border=NA,scales=list(x=list(at=c(-50,0,50)),y=list(draw=F),cex=1))+layer(panel.abline(v=0,col="red",lwd=2))
391 be7b1081 Adam M. Wilson
392
### regional plots
393 d39ab57e Adam M. Wilson
p1=useOuterStrips(levelplot(value~x*y|variable+trans,data=trd[!trd$variable%in%c("MOD17_unscaled","MOD11_unscaled","MCD12Q1","MOD35pp"),],asp=1,scales=list(draw=F,rot=0,relation="free"),
394 be7b1081 Adam M. Wilson
                                       at=at,col.regions=cols,maxpixels=7e6,
395 57d44dd9 Adam M. Wilson
                                       ylab="Latitude",xlab="Longitude"),strip.left=strip,strip = strip)+layer(sp.lines(trans,lwd=2))
396 be7b1081 Adam M. Wilson
397
p2=useOuterStrips(
398
  levelplot(value~x*y|variable+trans,data=trd[trd$variable%in%c("MCD12Q1"),],
399
            asp=1,scales=list(draw=F,rot=0,relation="free"),colorkey=F,
400
            at=c(-1,IGBP$ID),col.regions=IGBP$col,maxpixels=7e7,
401
            legend=list(
402
              right=list(fun=draw.key(list(columns=1,#title="MCD12Q1 \n IGBP Land \n Cover",
403
                           rectangles=list(col=IGBP$col,size=1),
404
                           text=list(as.character(IGBP$ID),at=IGBP$ID-.5))))),
405 57d44dd9 Adam M. Wilson
            ylab="",xlab=" "),strip = strip,strip.left=F)+layer(sp.lines(trans,lwd=2))
406 be7b1081 Adam M. Wilson
p3=useOuterStrips(
407
  levelplot(value~x*y|variable+trans,data=trd[trd$variable%in%c("MOD35pp"),],
408
            asp=1,scales=list(draw=F,rot=0,relation="free"),colorkey=F,
409
            at=c(-1:4),col.regions=c("blue","cyan","tan","darkgreen"),maxpixels=7e7,
410
            legend=list(
411
              right=list(fun=draw.key(list(columns=1,#title="MOD35 \n Processing \n Path",
412
                           rectangles=list(col=c("blue","cyan","tan","darkgreen"),size=1),
413
                           text=list(c("Water","Coast","Desert","Land")))))),
414 57d44dd9 Adam M. Wilson
            ylab="",xlab=" "),strip = strip,strip.left=F)+layer(sp.lines(trans,lwd=2))
415 be7b1081 Adam M. Wilson
416
## transects
417
p4=xyplot(value~dist|transect,groups=variable,type=c("smooth","p"),
418
       data=transd,panel=function(...,subscripts=subscripts) {
419
         td=transd[subscripts,]
420 ddd9a810 Adam M. Wilson
         ## mod09
421 d39ab57e Adam M. Wilson
         imod09=td$variable=="C5MOD09CF"
422 be7b1081 Adam M. Wilson
         panel.xyplot(td$dist[imod09],td$value[imod09],type=c("p","smooth"),span=0.2,subscripts=1:sum(imod09),col="red",pch=16,cex=.25)
423 ddd9a810 Adam M. Wilson
         ## mod35C5
424 be7b1081 Adam M. Wilson
         imod35=td$variable=="C5MOD35CF"
425
         panel.xyplot(td$dist[imod35],td$value[imod35],type=c("p","smooth"),span=0.09,subscripts=1:sum(imod35),col="blue",pch=16,cex=.25)
426
         ## mod35C6
427
         imod35c6=td$variable=="C6MOD35CF"
428
         panel.xyplot(td$dist[imod35c6],td$value[imod35c6],type=c("p","smooth"),span=0.09,subscripts=1:sum(imod35c6),col="black",pch=16,cex=.25)
429 ddd9a810 Adam M. Wilson
         ## mod17
430 be7b1081 Adam M. Wilson
         imod17=td$variable=="MOD17"
431
         panel.xyplot(td$dist[imod17],100*((td$value[imod17]-td$min[imod17][1])/(td$max[imod17][1]-td$min[imod17][1])),
432
                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="darkgreen",lty=5,pch=1,cex=.25)
433
         imod17qc=td$variable=="MOD17CF"
434
         panel.xyplot(td$dist[imod17qc],td$value[imod17qc],type=c("p","smooth"),span=0.09,subscripts=1:sum(imod17qc),col="darkgreen",pch=16,cex=.25)
435 ddd9a810 Adam M. Wilson
         ## mod11
436 be7b1081 Adam M. Wilson
         imod11=td$variable=="MOD11"
437
         panel.xyplot(td$dist[imod11],100*((td$value[imod11]-td$min[imod11][1])/(td$max[imod11][1]-td$min[imod11][1])),
438
                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="orange",lty="dashed",pch=1,cex=.25)
439
         imod11qc=td$variable=="MOD11CF"
440
         qcspan=ifelse(td$transect[1]=="Australia",0.2,0.05)
441
         panel.xyplot(td$dist[imod11qc],td$value[imod11qc],type=c("p","smooth"),npoints=100,span=qcspan,subscripts=1:sum(imod11qc),col="orange",pch=16,cex=.25)
442 ddd9a810 Adam M. Wilson
         ## land
443 be7b1081 Adam M. Wilson
         path=td[td$variable=="MOD35pp",]
444 d39ab57e Adam M. Wilson
         panel.segments(path$dist,-10,c(path$dist[-1],max(path$dist,na.rm=T)),-10,col=c("blue","cyan","tan","darkgreen")[path$value+1],subscripts=1:nrow(path),lwd=10,type="l")
445 be7b1081 Adam M. Wilson
         land=td[td$variable=="MCD12Q1",]
446 d39ab57e Adam M. Wilson
         panel.segments(land$dist,-20,c(land$dist[-1],max(land$dist,na.rm=T)),-20,col=IGBP$col[land$value+1],subscripts=1:nrow(land),lwd=10,type="l")
447 be7b1081 Adam M. Wilson
        },subscripts=T,par.settings = list(grid.pars = list(lineend = "butt")),
448 ddd9a810 Adam M. Wilson
       scales=list(
449 be7b1081 Adam M. Wilson
         x=list(alternating=1,relation="free"),#, lim=c(0,70)),
450 57d44dd9 Adam M. Wilson
         y=list(at=c(-20,-10,seq(0,100,len=5)),
451 d39ab57e Adam M. Wilson
           labels=c("MCD12Q1 IGBP","MOD35 path",seq(0,100,len=5)),
452
           lim=c(-25,100)),
453
         alternating=F),
454 be7b1081 Adam M. Wilson
       xlab="Distance Along Transect (km)", ylab="% Missing Data / % of Maximum Value",
455
       legend=list(
456 a57c4e3d Adam M. Wilson
         bottom=list(fun=draw.key(list( rep=FALSE,columns=1,title=" ",
457 d39ab57e Adam M. Wilson
                      lines=list(type=c("b","b","b","b","b","l","b","l"),pch=16,cex=.5,
458
                        lty=c(0,1,1,1,1,5,1,5),
459
                        col=c("transparent","red","blue","black","darkgreen","darkgreen","orange","orange")),
460
                       text=list(
461
                         c("MODIS Products","C5 MOD09 % Cloudy","C5 MOD35 % Cloudy","C6 MOD35 % Cloudy","MOD17 % Missing","MOD17 (scaled)","MOD11 % Missing","MOD11 (scaled)")),
462 a57c4e3d Adam M. Wilson
                       rectangles=list(border=NA,col=c(NA,"tan","darkgreen")),
463
                       text=list(c("C5 MOD35 Processing Path","Desert","Land")),
464 d39ab57e Adam M. Wilson
                       rectangles=list(border=NA,col=c(NA,IGBP$col[sort(unique(transd$value[transd$variable=="MCD12Q1"]+1))])),
465
                       text=list(c("MCD12Q1 IGBP Land Cover",IGBP$class[sort(unique(transd$value[transd$variable=="MCD12Q1"]+1))])))))),
466 57d44dd9 Adam M. Wilson
  strip = strip,strip.left=F)
467
#print(p4)
468 be7b1081 Adam M. Wilson
469
470
CairoPDF("output/mod35compare.pdf",width=11,height=7)
471
#CairoPNG("output/mod35compare_%d.png",units="in", width=11,height=8.5,pointsize=4000,dpi=1200,antialias="subpixel")
472
### Global Comparison
473 598244e1 Adam M. Wilson
print(g1,position=c(0,.35,1,1),more=T)
474
print(g2,position=c(0,0,1,0.415),more=F)
475
#print(g3,position=c(0.31,0.06,.42,0.27),more=F)
476
         
477 be7b1081 Adam M. Wilson
### MOD35 Desert Processing path
478 57d44dd9 Adam M. Wilson
levelplot(pp,asp=1,scales=list(draw=T,rot=0),maxpixels=1e6,cuts=3,
479
          at=(0:3)+.5,col.regions=c("blue","cyan","tan","darkgreen"),margin=F,
480
          colorkey=list(space="top",title="MOD35 Processing Path",labels=list(labels=c("Water","Coast","Desert","Land"),at=0:3),height=.25))+
481
  layer(sp.points(coordinates(bbs),col="black",cex=2,pch=13,lwd=2))+
482
  layer(sp.lines(coast,lwd=.5))
483
484 ddd9a810 Adam M. Wilson
### levelplot of regions
485 be7b1081 Adam M. Wilson
print(p1,position=c(0,0,.62,1),more=T)
486
print(p2,position=c(0.6,0.21,0.78,0.79),more=T)
487
print(p3,position=c(0.76,0.21,1,0.79))
488
### profile plots
489
print(p4)
490
dev.off()
491 ddd9a810 Adam M. Wilson
492 be7b1081 Adam M. Wilson
### summary stats for paper
493 598244e1 Adam M. Wilson
td=cast(transect+loc+dist~variable,value="value",data=transd)
494
td2=melt.data.frame(td,id.vars=c("transect","dist","loc","MOD35pp","MCD12Q1"))
495 ddd9a810 Adam M. Wilson
496 be7b1081 Adam M. Wilson
## function to prettyprint mean/sd's
497
msd= function(x) paste(round(mean(x,na.rm=T),1),"% ±",round(sd(x,na.rm=T),1),sep="")
498 ddd9a810 Adam M. Wilson
499 be7b1081 Adam M. Wilson
cast(td2,transect+variable~MOD35pp,value="value",fun=msd)
500
cast(td2,transect+variable~MOD35pp+MCD12Q1,value="value",fun=msd)
501
cast(td2,transect+variable~.,value="value",fun=msd)
502
503
cast(td2,transect+variable~.,value="value",fun=msd)
504
505
cast(td2,variable~MOD35pp,value="value",fun=msd)
506
cast(td2,variable~.,value="value",fun=msd)
507
508
td[td$transect=="Venezuela",]
509 ddd9a810 Adam M. Wilson
510
511 d39ab57e Adam M. Wilson
#### export KML
512 ddd9a810 Adam M. Wilson
library(plotKML)
513
514 d39ab57e Adam M. Wilson
kml_open("output/modiscloud.kml")
515 ddd9a810 Adam M. Wilson
516 d39ab57e Adam M. Wilson
readAll(mod35c5)
517 ddd9a810 Adam M. Wilson
518 d39ab57e Adam M. Wilson
kml_layer.Raster(mod35c5,
519 57d44dd9 Adam M. Wilson
     plot.legend = TRUE,raster_name="Collection 5 MOD35 2009 Cloud Frequency",
520 d39ab57e Adam M. Wilson
    z.lim = c(0,100),colour_scale = get("colour_scale_numeric", envir = plotKML.opts),
521 ddd9a810 Adam M. Wilson
#    home_url = get("home_url", envir = plotKML.opts),
522
#    metadata = NULL, html.table = NULL,
523 d39ab57e Adam M. Wilson
    altitudeMode = "clampToGround", balloon = FALSE
524 ddd9a810 Adam M. Wilson
)
525
526 d39ab57e Adam M. Wilson
system(paste("gdal_translate -of KMLSUPEROVERLAY ",mod35c5@file@name," output/mod35c5.kmz -co FORMAT=JPEG"))
527
528 ddd9a810 Adam M. Wilson
logo = "http://static.tumblr.com/t0afs9f/KWTm94tpm/yale_logo.png"
529
kml_screen(image.file = logo, position = "UL", sname = "YALE logo",size=c(.1,.1))
530 d39ab57e Adam M. Wilson
kml_close("modiscloud.kml")
531
kml_compress("modiscloud.kml",files=c(paste(month.name,".png",sep=""),"obj_legend.png"),zip="/usr/bin/zip")