Project

General

Profile

Download (23.6 KB) Statistics
| Branch: | Revision:
1
## 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
library(rgeos)
12
library(splancs)
13

    
14
## get % cloudy
15
mod09=raster("data/MOD09_2009.tif")
16
names(mod09)="C5MOD09CF"
17
NAvalue(mod09)=0
18

    
19
mod35c5=raster("data/MOD35_2009.tif")
20
names(mod35c5)="C5MOD35CF"
21
NAvalue(mod35c5)=0
22

    
23
## mod35C6 annual
24
if(!file.exists("data/MOD35C6_2009.tif")){
25
  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'` ")
26
#  system("gdalbuildvrt data/MOD35C6.vrt `find /home/adamw/acrobates/adamw/projects/interp/data/modis/mod35/summary/ -name '*h[1-9]*_mean.nc'` ")
27

    
28
#  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 4 -b 1 data/MOD35C6_CFday_pmiss.vrt `find /home/adamw/acrobates/adamw/projects/interp/data/modis/mod35/summary/ -name '*h[1]*.nc'` ")
29
#  system("gdalwarp data/MOD35C6_CFday_pmiss.vrt data/MOD35C6_CFday_pmiss.tif -r bilinear")
30

    
31
  system("align.sh data/MOD35C6.vrt data/MOD09_2009.tif data/MOD35C6_2009.tif")
32
#  system("align.sh data/MOD35C6_CFday_pmiss.vrt data/MOD09_2009.tif data/MOD35C6_CFday_pmiss.tif")
33
}
34
mod35c6=raster("data/MOD35C6_2009.tif")
35
names(mod35c6)="C6MOD35CF"
36
NAvalue(mod35c6)=255
37

    
38
## landcover
39
if(!file.exists("data/MCD12Q1_IGBP_2009_051_wgs84_1km.tif")){
40
  system(paste("/usr/local/gdal-1.10.0/bin/gdalwarp -tr 0.008983153 0.008983153 -r mode -ot Byte -co \"COMPRESS=LZW\"",
41
               " /mnt/data/jetzlab/Data/environ/global/MODIS/MCD12Q1/051/MCD12Q1_051_2009_wgs84.tif ",
42
               " -t_srs \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\" ",
43
               " -te -180.0044166 -60.0074610 180.0044166 90.0022083 ",
44
               "data/MCD12Q1_IGBP_2009_051_wgs84_1km.tif -overwrite ",sep=""))}
45
lulc=raster("data/MCD12Q1_IGBP_2009_051_wgs84_1km.tif")
46

    
47
#  lulc=ratify(lulc)
48
  data(worldgrids_pal)  #load palette
49
  IGBP=data.frame(ID=0:16,col=worldgrids_pal$IGBP[-c(18,19)],
50
    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)
51
  IGBP$class=rownames(IGBP);rownames(IGBP)=1:nrow(IGBP)
52
  levels(lulc)=list(IGBP)
53
#lulc=crop(lulc,mod09)
54
names(lulc)="MCD12Q1"
55

    
56
## make land mask
57
if(!file.exists("data/land.tif"))
58
  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)
59
land=raster("data/land.tif")
60

    
61
## mask cloud masks to land pixels
62
#mod09l=mask(mod09,land)
63
#mod35l=mask(mod35,land)
64

    
65
#####################################
66
### compare MOD43 and MOD17 products
67

    
68
## MOD17
69
#extent(mod17)=alignExtent(mod17,mod09)
70
if(!file.exists("data/MOD17.tif"))
71
system("align.sh ~/acrobates/adamw/projects/interp/data/modis/MOD17/MOD17A3_Science_NPP_mean_00_12.tif data/MOD09_2009.tif data/MOD17.tif")
72
mod17=raster("data/MOD17.tif",format="GTiff")
73
NAvalue(mod17)=65535
74
names(mod17)="MOD17_unscaled"
75

    
76
if(!file.exists("data/MOD17qc.tif"))
77
  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")
78
mod17qc=raster("data/MOD17qc.tif",format="GTiff")
79
NAvalue(mod17qc)=255
80
names(mod17qc)="MOD17CF"
81

    
82
## MOD11 via earth engine
83
if(!file.exists("data/MOD11_2009.tif"))
84
  system("align.sh ~/acrobates/adamw/projects/interp/data/modis/mod11/2009/MOD11_LST_2009.tif data/MOD09_2009.tif data/MOD11_2009.tif")
85
mod11=raster("data/MOD11_2009.tif",format="GTiff")
86
names(mod11)="MOD11_unscaled"
87
NAvalue(mod11)=0
88
if(!file.exists("data/MOD11qc_2009.tif"))
89
  system("align.sh ~/acrobates/adamw/projects/interp/data/modis/mod11/2009/MOD11_Pmiss_2009.tif data/MOD09_2009.tif data/MOD11qc_2009.tif")
90
mod11qc=raster("data/MOD11qc_2009.tif",format="GTiff")
91
names(mod11qc)="MOD11CF"
92

    
93
### Processing path
94
if(!file.exists("data/MOD35pp.tif"))
95
system("align.sh data/C5MOD35_ProcessPath.tif data/MOD09_2009.tif data/MOD35pp.tif")
96
pp=raster("data/MOD35pp.tif")
97
NAvalue(pp)=255
98
names(pp)="MOD35pp"
99

    
100

    
101
#hist(dif,maxsamp=1000000)
102
## draw lulc-stratified random sample of mod35-mod09 differences 
103
#samp=sampleStratified(lulc, 1000, exp=10)
104
#save(samp,file="LULC_StratifiedSample_10000.Rdata")
105
#mean(dif[samp],na.rm=T)
106
#Stats(dif,function(x) c(mean=mean(x),sd=sd(x)))
107

    
108

    
109
###
110

    
111
n=100
112
at=seq(0,100,len=n)
113
cols=grey(seq(0,1,len=n))
114
cols=rainbow(n)
115
bgyr=colorRampPalette(c("blue","green","yellow","red"))
116
cols=bgyr(n)
117

    
118

    
119
### Transects
120
r1=Lines(list(
121
  Line(matrix(c(
122
                -61.688,4.098,
123
                -59.251,3.430
124
                ),ncol=2,byrow=T))),"Venezuela")
125
r2=Lines(list(
126
  Line(matrix(c(
127
                133.746,-31.834,
128
                134.226,-32.143
129
                ),ncol=2,byrow=T))),"Australia")
130
r3=Lines(list(
131
  Line(matrix(c(
132
                73.943,27.419,
133
                74.369,26.877
134
                ),ncol=2,byrow=T))),"India")
135
r4=Lines(list(
136
  Line(matrix(c(
137
                33.195,12.512,
138
                33.802,12.894
139
                ),ncol=2,byrow=T))),"Sudan")
140

    
141

    
142

    
143
trans=SpatialLines(list(r1,r2,r3,r4),CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "))
144
### write out shapefiles of transects
145
writeOGR(SpatialLinesDataFrame(trans,data=data.frame(ID=names(trans)),match.ID=F),"output",layer="transects",driver="ESRI Shapefile",overwrite=T)
146

    
147
## buffer transects to get regional values 
148
transb=gBuffer(trans,byid=T,width=0.4)
149

    
150
## make polygons of bounding boxes
151
bb0 <- lapply(slot(transb, "polygons"), bbox)
152
bb1 <- lapply(bb0, bboxx)
153
# turn these into matrices using a helper function in splancs
154
bb2 <- lapply(bb1, function(x) rbind(x, x[1,]))
155
# close the matrix rings by appending the first coordinate
156
rn <- row.names(transb)
157
# get the IDs
158
bb3 <- vector(mode="list", length=length(bb2))
159
# make somewhere to keep the output
160
for (i in seq(along=bb3)) bb3[[i]] <- Polygons(list(Polygon(bb2[[i]])),
161
                   ID=rn[i])
162
# loop over the closed matrix rings, adding the IDs
163
bbs <- SpatialPolygons(bb3, proj4string=CRS(proj4string(transb)))
164

    
165
trd1=lapply(1:length(transb),function(x) {
166
  td=crop(mod11,transb[x])
167
  tdd=lapply(list(mod35c5,mod35c6,mod09,mod17,mod17qc,mod11,mod11qc,lulc,pp),function(l) resample(crop(l,transb[x]),td,method="ngb"))
168
  ## normalize MOD11 and MOD17
169
  for(j in which(do.call(c,lapply(tdd,function(i) names(i)))%in%c("MOD11_unscaled","MOD17_unscaled"))){
170
    trange=cellStats(tdd[[j]],range)
171
    tscaled=100*(tdd[[j]]-trange[1])/(trange[2]-trange[1])
172
    tscaled@history=list(range=trange)
173
    names(tscaled)=sub("_unscaled","",names(tdd[[j]]))
174
    tdd=c(tdd,tscaled)
175
  }
176
  return(brick(tdd))
177
})
178

    
179
## bind all subregions into single dataframe for plotting
180
trd=do.call(rbind.data.frame,lapply(1:length(trd1),function(i){
181
  d=as.data.frame(as.matrix(trd1[[i]]))
182
  d[,c("x","y")]=coordinates(trd1[[i]])
183
  d$trans=names(trans)[i]
184
  d=melt(d,id.vars=c("trans","x","y"))
185
  return(d)
186
}))
187

    
188
transd=do.call(rbind.data.frame,lapply(1:length(trans),function(l) {
189
  td=as.data.frame(extract(trd1[[l]],trans[l],along=T,cellnumbers=F)[[1]])
190
  td$loc=extract(trd1[[l]],trans[l],along=T,cellnumbers=T)[[1]][,1]
191
  td[,c("x","y")]=xyFromCell(trd1[[l]],td$loc)
192
  td$dist=spDistsN1(as.matrix(td[,c("x","y")]), as.matrix(td[1,c("x","y")]),longlat=T)
193
  td$transect=names(trans[l])
194
  td2=melt(td,id.vars=c("loc","x","y","dist","transect"))
195
  td2=td2[order(td2$variable,td2$dist),]
196
  # get per variable ranges to normalize
197
  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)
198
  td2$min=tr$min[match(td2$variable,tr$L1)]
199
  td2$max=tr$max[match(td2$variable,tr$L1)]
200
  print(paste("Finished ",names(trans[l])))
201
  return(td2)}
202
  ))
203

    
204
transd$type=ifelse(grepl("MOD35|MOD09|CF",transd$variable),"CF","Data")
205

    
206

    
207
## comparison of % cloudy days
208
if(!file.exists("data/dif_c5_09.tif"))
209
  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)
210
dif_c5_09=raster("data/dif_c5_09.tif",format="GTiff")
211

    
212
#dif_c6_09=mod35c6-mod09
213
#dif_c5_c6=mod35c5-mod35c6
214

    
215
##################################################################################
216
## Identify problematic areas with hard edges in cloud frequency
217
############################
218
library(multicore)
219

    
220
## set up processing chunks
221
nrw=nrow(mod35c5)
222
nby=10
223
nrwg=seq(1,nrw,by=nby)
224
writeLines(paste("Processing ",length(nrwg)," groups and",nrw,"lines"))
225

    
226
## Parallel loop to conduct moving window analysis and quantify pixels with significant shifts across pp or lulc boundaries
227
output=mclapply(nrwg,function(ti){
228
  ## Extract focal areas 
229
  ngb=5
230
  vals=getValuesFocal(mod35c5,ngb=ngb,row=ti,nrows=nby)
231
  vals_mod09=getValuesFocal(mod09,ngb=ngb,row=ti,nrows=nby)
232
  pp_ind=getValuesFocal(pp,ngb=ngb,row=ti,nrows=nby)
233
  lulc_ind=getValuesFocal(lulc,ngb=ngb,row=ti,nrows=nby)
234
  ## processing path
235
  pp_bias=raster(matrix(do.call(rbind,lapply(1:nrow(vals),function(i) {
236
    tind1=pp_ind[i,]  #vector of indices
237
    tval1=vals[i,]    # vector of values
238
    tind2=tind1[!is.na(tind1)&!is.na(tval1)]  #which classes exist without NAs?
239
    if(length(unique(tind2))<2) return(255)  #if only one class, return 255
240
    if(sort(table(tind2),dec=T)[2]<5) return(254) # if too few observations of class 2, return 254
241
    return(round(kruskal.test(tval1,tind1)$p.value*100))         # if it works, return p.value*100
242
  })),nrow=nby,ncol=ncol(mod35c5),byrow=T))     # turn it back into a raster
243
  ## udpate raster and write it
244
  extent(pp_bias)=extent(mod35c5[ti:(ti+nby-1),1:ncol(mod35c5),drop=F])
245
  projection(pp_bias)=projection(mod35c5)
246
  NAvalue(pp_bias) <- 255
247
  writeRaster(pp_bias,file=paste("data/tiles/pp_bias_",ti,".tif",sep=""),
248
              format="GTiff",dataType="INT1U",overwrite=T,NAflag=255) #,options=c("COMPRESS=LZW","ZLEVEL=9")
249
  ## landcover
250
  lulc_bias=raster(matrix(do.call(rbind,lapply(1:nrow(vals),function(i) {
251
    tind1=lulc_ind[i,]  #vector of indices
252
    tval1=vals[i,]    # vector of values
253
    tind2=tind1[!is.na(tind1)&!is.na(tval1)]  #which classes exist without NAs?
254
    if(length(unique(tind2))<2) return(255)  #if only one class, return 255
255
    if(sort(table(tind2),dec=T)[2]<5) return(254) # if too few observations of class 2, return 254
256
    return(round(kruskal.test(tval1,tind1)$p.value*100))         # if it works, get p.value*100
257
  })),nrow=nby,ncol=ncol(mod35c5),byrow=T))     # turn it back into a raster
258
  ## udpate raster and write it
259
  extent(lulc_bias)=extent(mod35c5[ti:(ti+nby-1),1:ncol(mod35c5),drop=F])
260
  projection(lulc_bias)=projection(mod35c5)
261
  NAvalue(lulc_bias) <- 255
262
  writeRaster(lulc_bias,file=paste("data/tiles/lulc_bias_",ti,".tif",sep=""),
263
              format="GTiff",dataType="INT1U",overwrite=T,NAflag=255)#,options=c("COMPRESS=LZW","ZLEVEL=9")
264

    
265
    ## MOD09
266
  mod09_lulc_bias=raster(matrix(do.call(rbind,lapply(1:nrow(vals_mod09),function(i) {
267
    tind1=lulc_ind[i,]  #vector of indices
268
    tval1=vals_mod09[i,]    # vector of values
269
    tind2=tind1[!is.na(tind1)&!is.na(tval1)]  #which classes exist without NAs?
270
    if(length(unique(tind2))<2) return(255)  #if only one class, return 255
271
    if(sort(table(tind2),dec=T)[2]<5) return(254) # if too few observations of class 2, return 254
272
    return(round(kruskal.test(tval1,tind1)$p.value*100))         # if it works, get p.value*100
273
  })),nrow=nby,ncol=ncol(mod35c5),byrow=T))     # turn it back into a raster
274
  ## udpate raster and write it
275
  extent(mod09_lulc_bias)=extent(mod09[ti:(ti+nby-1),1:ncol(mod09),drop=F])
276
  projection(mod09_lulc_bias)=projection(mod09)
277
  NAvalue(mod09_lulc_bias) <- 255
278
  writeRaster(mod09_lulc_bias,file=paste("data/tiles/mod09_lulc_bias_",ti,".tif",sep=""),
279
              format="GTiff",dataType="INT1U",overwrite=T,NAflag=255)#,options=c("COMPRESS=LZW","ZLEVEL=9")
280

    
281
  return(ti)
282
},mc.cores=15)
283

    
284

    
285
### check raster temporary files
286
showTmpFiles()
287
#removeTmpFiles(h=1)
288

    
289
## merge all the files back again
290
  system("gdalbuildvrt -srcnodata 255 -vrtnodata 255 data/lulc_bias.vrt `find data/tiles -name 'lulc_bias*tif'` ")
291
  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")
292
#  system("align.sh data/lulc_bias.vrt data/MOD09_2009.tif data/lulc_bias.tif")
293

    
294
  system("gdalbuildvrt data/pp_bias.vrt `find data/tiles -name 'pp_bias*tif'` ")
295
  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")
296
  system("align.sh -srcnodata 255 -dstnodata 255 -multi -r bilinear data/pp_bias.vrt data/MOD09_2009.tif data/pp_bias_align.tif &")
297

    
298
  system("gdalbuildvrt data/mod09_lulc_bias.vrt `find data/tiles -name 'mod09_lulc_bias*tif'` ")
299
  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")
300

    
301
### read them back in
302
pp_bias=raster("data/pp_bias.tif")
303
names(pp_bias)="Processing Path"
304
lulc_bias=raster("data/lulc_bias.tif")
305
names(lulc_bias)="Land Use Land Cover"
306

    
307
pat=c(0,0.05,1)#seq(0,0.-5,len=2) #,seq(0.05,.1,len=50))
308
grayr2=colorRampPalette(c("red","transparent"))#grey(c(.75,.5,.25))))
309
levelplot(stack(pp_bias,lulc_bias),col.regions=c(grayr2(2)),at=pat,
310
          colorkey=F,margin=F,maxpixels=1e6)+layer(sp.lines(coast,lwd=.5))
311

    
312
cor(td1$MOD17,td1$C6MOD35,use="complete",method="spearman")
313
cor(td1$MOD17[td1$edgeb==1],td1$C5MOD35[td1$edgeb==1],use="complete",method="spearman")
314

    
315
bwplot(value~MOD35pp|variable,data=td1l[td1l$pedgeb==1,],horizontal=F)
316

    
317
crosstab(dif_c5_09,pp)
318
### Correlations
319
#trdw=cast(trd,trans+x+y~variable,value="value")
320
#cor(trdw$MOD17,trdw$C5MOD35,use="complete",method="spearman")
321

    
322
#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.  
323
#by(trdw,trdw$trans,function(x) cor(as.data.frame(na.omit(x[,c("C5MOD35CF","C6MOD35CF","C5MOD09CF","MOD17","MOD11")])),use="complete",method="spearman"))
324

    
325

    
326
## table of correlations
327
#trdw_cor=as.data.frame(na.omit(trdw[,c("C5MOD35CF","C6MOD35CF","C5MOD09CF","MOD17","MOD11")]))
328
#nrow(trdw_cor)
329
#round(cor(trdw_cor,method="spearman"),2)
330

    
331

    
332
## set up some graphing parameters
333
at=seq(0,100,leng=100)
334
bgyr=colorRampPalette(c("purple","blue","green","yellow","orange","red","red"))
335
bgray=colorRampPalette(c("purple","blue","deepskyblue4"))
336
grayr=colorRampPalette(c("grey","red","darkred"))
337
bgrayr=colorRampPalette(c("darkblue","blue","grey","red","purple"))
338

    
339
cols=bgyr(100)
340

    
341
strip=strip.custom(par.strip.text=list(cex=.7),bg="transparent")
342

    
343
## global map
344
library(maptools)
345
coast=map2SpatialLines(map("world", interior=FALSE, plot=FALSE),proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
346

    
347
g1=levelplot(stack(mod35c5,mod35c6,mod09),xlab=" ",scales=list(x=list(draw=F),y=list(alternating=1)),
348
  col.regions=cols,at=at,cuts=length(at),maxpixels=1e6,
349
  colorkey=list(at=at))+
350
#  layer(sp.polygons(bbs,lwd=5,col="black"))+
351
  layer(sp.lines(coast,lwd=.5))+
352
  layer(sp.points(coordinates(bbs),col="black",cex=2,pch=13,lwd=2))
353

    
354
### Plot of differences between MOD09 adn MOD35 masks
355
#system("gdalinfo -stats /home/adamw/acrobates/adamw/projects/MOD35C5/data/dif_c5_09.tif")
356
## get quantiles for color bar of differences
357
#qs=unique(quantile(as.vector(as.matrix(dif_c5_09)),seq(0,1,len=100),na.rm=T))
358
#c(bgray(sum(qs<0)),grayr(sum(qs>=0)+1))
359
qs=seq(-80,80,len=100)
360
g2=levelplot(dif_c5_09,col.regions=bgrayr(100),cuts=100,at=qs,margin=F,ylab=" ",colorkey=list("right",at=qs),maxpixels=1e6)+
361
  layer(sp.points(coordinates(bbs),col="black",cex=2,pch=13,lwd=2))+
362
  #layer(sp.polygons(bbs,lwd=2))+
363
  layer(sp.lines(coast,lwd=.5))
364

    
365
g2$strip=strip.custom(var.name="Difference (C5MOD35-C5MOD09)",style=1,strip.names=T,strip.levels=F)  #update strip text
366
#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))
367

    
368
### regional plots
369
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"),
370
                                       at=at,col.regions=cols,maxpixels=7e6,
371
                                       ylab="Latitude",xlab="Longitude"),strip.left=strip,strip = strip)+layer(sp.lines(trans,lwd=2))
372

    
373
p2=useOuterStrips(
374
  levelplot(value~x*y|variable+trans,data=trd[trd$variable%in%c("MCD12Q1"),],
375
            asp=1,scales=list(draw=F,rot=0,relation="free"),colorkey=F,
376
            at=c(-1,IGBP$ID),col.regions=IGBP$col,maxpixels=7e7,
377
            legend=list(
378
              right=list(fun=draw.key(list(columns=1,#title="MCD12Q1 \n IGBP Land \n Cover",
379
                           rectangles=list(col=IGBP$col,size=1),
380
                           text=list(as.character(IGBP$ID),at=IGBP$ID-.5))))),
381
            ylab="",xlab=" "),strip = strip,strip.left=F)+layer(sp.lines(trans,lwd=2))
382
p3=useOuterStrips(
383
  levelplot(value~x*y|variable+trans,data=trd[trd$variable%in%c("MOD35pp"),],
384
            asp=1,scales=list(draw=F,rot=0,relation="free"),colorkey=F,
385
            at=c(-1:4),col.regions=c("blue","cyan","tan","darkgreen"),maxpixels=7e7,
386
            legend=list(
387
              right=list(fun=draw.key(list(columns=1,#title="MOD35 \n Processing \n Path",
388
                           rectangles=list(col=c("blue","cyan","tan","darkgreen"),size=1),
389
                           text=list(c("Water","Coast","Desert","Land")))))),
390
            ylab="",xlab=" "),strip = strip,strip.left=F)+layer(sp.lines(trans,lwd=2))
391

    
392
## transects
393
p4=xyplot(value~dist|transect,groups=variable,type=c("smooth","p"),
394
       data=transd,panel=function(...,subscripts=subscripts) {
395
         td=transd[subscripts,]
396
         ## mod09
397
         imod09=td$variable=="C5MOD09CF"
398
         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)
399
         ## mod35C5
400
         imod35=td$variable=="C5MOD35CF"
401
         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)
402
         ## mod35C6
403
         imod35c6=td$variable=="C6MOD35CF"
404
         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)
405
         ## mod17
406
         imod17=td$variable=="MOD17"
407
         panel.xyplot(td$dist[imod17],100*((td$value[imod17]-td$min[imod17][1])/(td$max[imod17][1]-td$min[imod17][1])),
408
                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="darkgreen",lty=5,pch=1,cex=.25)
409
         imod17qc=td$variable=="MOD17CF"
410
         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)
411
         ## mod11
412
         imod11=td$variable=="MOD11"
413
         panel.xyplot(td$dist[imod11],100*((td$value[imod11]-td$min[imod11][1])/(td$max[imod11][1]-td$min[imod11][1])),
414
                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="orange",lty="dashed",pch=1,cex=.25)
415
         imod11qc=td$variable=="MOD11CF"
416
         qcspan=ifelse(td$transect[1]=="Australia",0.2,0.05)
417
         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)
418
         ## land
419
         path=td[td$variable=="MOD35pp",]
420
         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")
421
         land=td[td$variable=="MCD12Q1",]
422
         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")
423
        },subscripts=T,par.settings = list(grid.pars = list(lineend = "butt")),
424
       scales=list(
425
         x=list(alternating=1,relation="free"),#, lim=c(0,70)),
426
         y=list(at=c(-20,-10,seq(0,100,len=5)),
427
           labels=c("MCD12Q1 IGBP","MOD35 path",seq(0,100,len=5)),
428
           lim=c(-25,100)),
429
         alternating=F),
430
       xlab="Distance Along Transect (km)", ylab="% Missing Data / % of Maximum Value",
431
       legend=list(
432
         bottom=list(fun=draw.key(list( rep=FALSE,columns=1,title=" ",
433
                      lines=list(type=c("b","b","b","b","b","l","b","l"),pch=16,cex=.5,
434
                        lty=c(0,1,1,1,1,5,1,5),
435
                        col=c("transparent","red","blue","black","darkgreen","darkgreen","orange","orange")),
436
                       text=list(
437
                         c("MODIS Products","C5 MOD09 % Cloudy","C5 MOD35 % Cloudy","C6 MOD35 % Cloudy","MOD17 % Missing","MOD17 (scaled)","MOD11 % Missing","MOD11 (scaled)")),
438
                       rectangles=list(border=NA,col=c(NA,"tan","darkgreen")),
439
                       text=list(c("C5 MOD35 Processing Path","Desert","Land")),
440
                       rectangles=list(border=NA,col=c(NA,IGBP$col[sort(unique(transd$value[transd$variable=="MCD12Q1"]+1))])),
441
                       text=list(c("MCD12Q1 IGBP Land Cover",IGBP$class[sort(unique(transd$value[transd$variable=="MCD12Q1"]+1))])))))),
442
  strip = strip,strip.left=F)
443
#print(p4)
444

    
445

    
446
CairoPDF("output/mod35compare.pdf",width=11,height=7)
447
#CairoPNG("output/mod35compare_%d.png",units="in", width=11,height=8.5,pointsize=4000,dpi=1200,antialias="subpixel")
448
### Global Comparison
449
print(g1,position=c(0,.35,1,1),more=T)
450
print(g2,position=c(0,0,1,0.415),more=F)
451
#print(g3,position=c(0.31,0.06,.42,0.27),more=F)
452
         
453
### MOD35 Desert Processing path
454
levelplot(pp,asp=1,scales=list(draw=T,rot=0),maxpixels=1e6,cuts=3,
455
          at=(0:3)+.5,col.regions=c("blue","cyan","tan","darkgreen"),margin=F,
456
          colorkey=list(space="top",title="MOD35 Processing Path",labels=list(labels=c("Water","Coast","Desert","Land"),at=0:3),height=.25))+
457
  layer(sp.points(coordinates(bbs),col="black",cex=2,pch=13,lwd=2))+
458
  layer(sp.lines(coast,lwd=.5))
459

    
460
### levelplot of regions
461
print(p1,position=c(0,0,.62,1),more=T)
462
print(p2,position=c(0.6,0.21,0.78,0.79),more=T)
463
print(p3,position=c(0.76,0.21,1,0.79))
464
### profile plots
465
print(p4)
466
dev.off()
467

    
468
### summary stats for paper
469
td=cast(transect+loc+dist~variable,value="value",data=transd)
470
td2=melt.data.frame(td,id.vars=c("transect","dist","loc","MOD35pp","MCD12Q1"))
471

    
472
## function to prettyprint mean/sd's
473
msd= function(x) paste(round(mean(x,na.rm=T),1),"% ±",round(sd(x,na.rm=T),1),sep="")
474

    
475
cast(td2,transect+variable~MOD35pp,value="value",fun=msd)
476
cast(td2,transect+variable~MOD35pp+MCD12Q1,value="value",fun=msd)
477
cast(td2,transect+variable~.,value="value",fun=msd)
478

    
479
cast(td2,transect+variable~.,value="value",fun=msd)
480

    
481
cast(td2,variable~MOD35pp,value="value",fun=msd)
482
cast(td2,variable~.,value="value",fun=msd)
483

    
484
td[td$transect=="Venezuela",]
485

    
486

    
487
#### export KML
488
library(plotKML)
489

    
490
kml_open("output/modiscloud.kml")
491

    
492
readAll(mod35c5)
493

    
494
kml_layer.Raster(mod35c5,
495
     plot.legend = TRUE,raster_name="Collection 5 MOD35 2009 Cloud Frequency",
496
    z.lim = c(0,100),colour_scale = get("colour_scale_numeric", envir = plotKML.opts),
497
#    home_url = get("home_url", envir = plotKML.opts),
498
#    metadata = NULL, html.table = NULL,
499
    altitudeMode = "clampToGround", balloon = FALSE
500
)
501

    
502
system(paste("gdal_translate -of KMLSUPEROVERLAY ",mod35c5@file@name," output/mod35c5.kmz -co FORMAT=JPEG"))
503

    
504
logo = "http://static.tumblr.com/t0afs9f/KWTm94tpm/yale_logo.png"
505
kml_screen(image.file = logo, position = "UL", sname = "YALE logo",size=c(.1,.1))
506
kml_close("modiscloud.kml")
507
kml_compress("modiscloud.kml",files=c(paste(month.name,".png",sep=""),"obj_legend.png"),zip="/usr/bin/zip")
(20-20/42)