Project

General

Profile

« Previous | Next » 

Revision be7b1081

Added by Adam Wilson over 11 years ago

Added script to make GHCN station shapefile for global station gap analysis

View differences:

climate/procedures/MOD35C5_Evaluation.r
8 8
library(plotKML)
9 9
library(Cairo)
10 10
library(reshape)
11
library(rgeos)
11 12

  
12
## get % cloudy
13
mod09=raster("data/MOD09_2009.tif")
14
names(mod09)="MOD09_cloud"
15

  
16
mod35c5=raster("data/MOD35_2009.tif")
17
mod35c5=crop(mod35c5,mod09)
18
names(mod35c5)="MOD35C5_cloud"
19

  
20
mod35c6=raster("")
21
 
22 13
## landcover
23 14
if(!file.exists("data/MCD12Q1_IGBP_2005_v51_1km_wgs84.tif")){
24 15
  system(paste("gdalwarp -r near -ot Byte -co \"COMPRESS=LZW\"",
......
34 25
  },file=paste(tempdir(),"/1km.tif",sep=""))
35 26
  writeRaster(lulc2,"data/MCD12Q1_IGBP_2005_v51_1km_wgs84.tif",options=c("COMPRESS=LZW","ZLEVEL=9","PREDICTOR=2"),datatype="INT1U",overwrite=T)
36 27
}
28
## read it in
37 29
lulc=raster("data/MCD12Q1_IGBP_2005_v51_1km_wgs84.tif")
38 30
#  lulc=ratify(lulc)
39 31
  data(worldgrids_pal)  #load palette
......
45 37
names(lulc)="MCD12Q1"
46 38

  
47 39
## make land mask
48
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)
40
if(!file.exists("data/land.tif"))
41
  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)
49 42
land=raster("data/land.tif")
50 43

  
44
## get % cloudy
45
mod09=raster("data/MOD09_2009.tif")
46
names(mod09)="MOD09CF"
47
NAvalue(mod09)=0
48

  
49
mod35c5=raster("data/MOD35_2009.tif")
50
mod35c5=crop(mod35c5,mod09)
51
names(mod35c5)="C5MOD35CF"
52
NAvalue(mod35c5)=0
53

  
54
system("gdalinfo /home/adamw/acrobates/adamw/projects/interp/data/modis/mod35/summary/.nc")
55

  
56
## mod35C6 annual
57
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 /home/adamw/acrobates/adamw/projects/interp/data/modis/mod35/summary/*2009mean.nc ")
58
system("align.sh data/MOD35C6.vrt data/MOD35_2009.tif data/MOD35C6_2009.tif")
59
mod35c6=raster("data/MOD35C6_2009.tif")
60
mod35c6=crop(mod35c6,mod09)
61
names(mod35c6)="C6MOD35CF"
62
NAvalue(mod35c6)=255
63

  
64
## Monthly
65
#system("find /home/adamw/acrobates/adamw/projects/interp/data/modis/mod35/summary/  -name '*[0-9].nc' > data/summaryfiles.txt")
66
#system("/usr/local/gdal-1.10.0/bin/gdalbuidvrt -allow_projection_difference -b 1 -sd 1 data/MOD35C6_monthly.vrt  ")
67
##system("/usr/local/gdal-1.10.0/bin/gdalwarp --optfile data/summaryfiles.txt data/MOD35C6_monthly.tif  ")#
68
#system("/usr/local/gdal-1.10.0/bin/gdal_translate -stats -co \"COMPRESS=LZW\" -of GTiff data/MOD35C6_monthly.vrt data/MOD35C6_monthly.tif ")
69

  
70
## nobs
71
#system("/usr/local/gdal-1.10.0/bin/gdalbuildvrt -allow_projection_difference -sd 4 data/MOD35C6_monthlypmiss.vrt `find /home/adamw/acrobates/adamw/projects/interp/data/modis/mod35/summary/  -name '*[0-9].nc'` ")
72
#system("/usr/local/gdal-1.10.0/bin/gdal_translate -stats -co \"COMPRESS=LZW\" -of GTiff data/MOD35C6_monthlypmiss.vrt data/MOD35C6_monthlypmiss.tif ")
73

  
74
                                        #mod35c6=raster("")
75
 
76
## mask cloud masks to land pixels
77
#mod09l=mask(mod09,land)
78
#mod35l=mask(mod35,land)
79

  
51 80
#####################################
52 81
### compare MOD43 and MOD17 products
53 82

  
......
62 91
NAvalue(mod17qc)=255
63 92
                                        #extent(mod17qc)=alignExtent(mod17qc,mod09)
64 93
mod17qc=crop(mod17qc,mod09)
65
names(mod17qc)="MOD17qc"
94
names(mod17qc)="MOD17CF"
66 95

  
67 96
## MOD11 via earth engine
68
mod11=raster("data/MOD11_2009.tif",format="GTiff")
97
mod11=raster("data/MOD11_LST_2009.tif",format="GTiff")
69 98
names(mod11)="MOD11"
99
NAvalue(mod11)=0
70 100
mod11qc=raster("data/MOD11_Pmiss_2009.tif",format="GTiff")
71
names(mod11qc)="MOD11qc"
101
names(mod11qc)="MOD11CF"
72 102

  
73 103
## MOD43 via earth engine
74
mod43=raster("data/mod43_2009.tif",format="GTiff")
75
mod43qc=raster("data/mod43_2009.tif",format="GTiff")
104
#mod43=raster("data/mod43_2009.tif",format="GTiff")
105
#mod43qc=raster("data/mod43_2009.tif",format="GTiff")
76 106

  
77 107

  
78 108
### Create some summary objects for plotting
......
82 112

  
83 113
### Processing path
84 114
pp=raster("data/MOD35_ProcessPath.tif")
85
extent(pp)=alignExtent(pp,mod09)
86
pp=crop(pp,mod09)
115
#rclmat=matrix( c(0, 0, 0, 1, 1, 11, 2, 2, 16, 3, 3, 1), ncol=3, byrow=TRUE)
116
#reclassify(pp,rclmat,file="data/MOD35_ProcessPath_reclass.tif",options=c("COMPRESS=LZW","ZLEVEL=9","PREDICTOR=2"),datatype="INT1U",overwrite=T)
117
#pp=raster("data/MOD35_ProcessPath_reclass.tif")
118
NAvalue(pp)=255
119
names(pp)="MOD35pp"
120
                                        #extent(pp)=alignExtent(pp,mod09)
121
#pp=crop(pp,mod09)
87 122

  
88 123
## Summary plot of mod17 and mod43
89
modprod=stack(mod35c5,mod09,pp,lulc)#,mod43,mod43qc)
90
names(modprod)=c("MOD17","MOD17qc")#,"MOD43","MOD43qc")
124
#modprod=stack(mod35c5,mod09,pp,lulc)#,mod43,mod43qc)
125
#names(modprod)=c("MOD17","MOD17qc")#,"MOD43","MOD43qc")
91 126

  
92 127

  
93 128
## comparison of % cloudy days
94
dif=mod35c5-mod09
95
hist(dif,maxsamp=1000000)
129
dif_c5_09=mod35c5-mod09
130
dif_c6_09=mod35c6-mod09
131
dif_c5_c6=mod35c5-mod35c6
96 132

  
97
## draw lulc-stratified random sample of mod35-mod09 differences 
98
samp=sampleStratified(lulc, 1000, exp=10)
99
save(samp,file="LULC_StratifiedSample_10000.Rdata")
100 133

  
101
mean(dif[samp],na.rm=T)
134
#hist(dif,maxsamp=1000000)
102 135

  
103
Stats(dif,function(x) c(mean=mean(x),sd=sd(x)))
136
## draw lulc-stratified random sample of mod35-mod09 differences 
137
#samp=sampleStratified(lulc, 1000, exp=10)
138
#save(samp,file="LULC_StratifiedSample_10000.Rdata")
139
#mean(dif[samp],na.rm=T)
140
#Stats(dif,function(x) c(mean=mean(x),sd=sd(x)))
104 141

  
105 142

  
106 143
###
......
114 151

  
115 152
#levelplot(lulcf,margin=F,layers="LULC")
116 153

  
117
CairoPDF("output/mod35compare.pdf",width=11,height=8.5)
118
#CairoPNG("output/mod35compare_%d.png",units="in", width=11,height=8.5,pointsize=4000,dpi=1200,antialias="subpixel")
119 154

  
120 155
### Transects
156
#r1=Lines(list(
157
#  Line(matrix(c(
158
#                -61.183,1.165,
159
#                -60.881,0.825
160
#                -60.106, 3.809,
161
#                -60.847,3.240
162
#                ),ncol=2,byrow=T))),"Venezuela")
121 163
r1=Lines(list(
122 164
  Line(matrix(c(
123
                -61.183,1.165,
124
                -60.881,0.825
165
                -61.688,4.098,
166
                -59.251,3.430
125 167
                ),ncol=2,byrow=T))),"Venezuela")
126 168
r2=Lines(list(
127 169
  Line(matrix(c(
......
141 183

  
142 184
r5=Lines(list(
143 185
  Line(matrix(c(
144
                24.170,-17.769,
145
                24.616,-18.084
146
                ),ncol=2,byrow=T))),"Africa")
147

  
148

  
149
trans=SpatialLines(list(r1,r2,r3,r4,r5),CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "))
150

  
151
transd=lapply(list(mod35c5,mod09,mod17,mod17qc,mod11qc,lulc,pp),function(l) {
152
  td=extract(l,trans,along=T,cellnumbers=F)
153
  names(td)=names(trans)                                        #  colnames(td)=c("value","transect")
154
  cells=extract(l,trans,along=T,cellnumbers=T)
155
  cells2=lapply(cells,function(x) xyFromCell(l,x[,1]))
156
  dists=lapply(cells2,function(x) spDistsN1(x,x[1,],longlat=T))
157
  td2=do.call(rbind.data.frame,lapply(1:length(td),function(i) cbind.data.frame(value=td[[i]],cells2[[i]],dist=dists[[i]],transect=names(td)[i])))
158
  td2$prod=names(l)
159
  td2$loc=rownames(td2)
160
  td2=td2[order(td2$dist),]
161
  print(paste("Finished ",names(l)))
186
                33.195,12.512,
187
                33.802,12.894
188
                ),ncol=2,byrow=T))),"Sudan")
189

  
190
r6=Lines(list(
191
  Line(matrix(c(
192
                -63.353,-10.746,
193
                -63.376,-9.310
194
                ),ncol=2,byrow=T))),"Brazil")
195

  
196

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

  
201
## buffer transects to get regional values 
202
transb=gBuffer(trans,0.4)
203

  
204
## make polygons of bounding boxes
205
bb0 <- lapply(slot(transb, "polygons"), bbox)
206
library(splancs)
207
bb1 <- lapply(bb0, bboxx)
208
# turn these into matrices using a helper function in splancs
209
bb2 <- lapply(bb1, function(x) rbind(x, x[1,]))
210
# close the matrix rings by appending the first coordinate
211
rn <- row.names(transb)
212
# get the IDs
213
bb3 <- vector(mode="list", length=length(bb2))
214
# make somewhere to keep the output
215
for (i in seq(along=bb3)) bb3[[i]] <- Polygons(list(Polygon(bb2[[i]])),
216
                   ID=rn[i])
217
# loop over the closed matrix rings, adding the IDs
218
bbs <- SpatialPolygons(bb3, proj4string=CRS(proj4string(transb)))
219

  
220

  
221
trd1=lapply(1:length(transb),function(x) {
222
  td=crop(mod11,transb[x])
223
  tdd=lapply(list(mod35c5,mod35c6,mod09,mod17,mod17qc,mod11,mod11qc,lulc,pp),function(l) resample(crop(l,transb[x]),td,method="ngb"))
224
  ## normalize MOD11 and MOD17
225
  for(j in which(do.call(c,lapply(tdd,function(i) names(i)))%in%c("MOD11","MOD17"))){
226
    trange=cellStats(tdd[[j]],range)
227
    tdd[[j]]=100*(tdd[[j]]-trange[1])/(trange[2]-trange[1])
228
    tdd[[j]]@history=list(range=trange)
229
  }
230
  return(brick(tdd))
231
})
232

  
233
## bind all subregions into single dataframe for plotting
234
trd=do.call(rbind.data.frame,lapply(1:length(trd1),function(i){
235
  d=as.data.frame(as.matrix(trd1[[i]]))
236
  d[,c("x","y")]=coordinates(trd1[[i]])
237
  d$trans=names(trans)[i]
238
  d=melt(d,id.vars=c("trans","x","y"))
239
  return(d)
240
}))
241

  
242
transd=do.call(rbind.data.frame,lapply(1:length(trans),function(l) {
243
  td=as.data.frame(extract(trd1[[l]],trans[l],along=T,cellnumbers=F)[[1]])
244
  td$loc=extract(trd1[[l]],trans[l],along=T,cellnumbers=T)[[1]][,1]
245
  td[,c("x","y")]=xyFromCell(trd1[[l]],td$loc)
246
  td$dist=spDistsN1(as.matrix(td[,c("x","y")]), as.matrix(td[1,c("x","y")]),longlat=T)
247
  td$transect=names(trans[l])
248
  td2=melt(td,id.vars=c("loc","x","y","dist","transect"))
249
  td2=td2[order(td2$variable,td2$dist),]
250
  # get per variable ranges to normalize
251
  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)
252
  td2$min=tr$min[match(td2$variable,tr$L1)]
253
  td2$max=tr$max[match(td2$variable,tr$L1)]
254
  print(paste("Finished ",names(trans[l])))
162 255
  return(td2)}
163
  )
164
transdl=melt(transd,id.vars=c("prod","transect","loc","x","y","dist"))
165
transd$loc=as.numeric(transd$loc)
166
transdl$type=ifelse(grepl("MOD35|MOD09|qc",transdl$prod),"QC","Data")
167
  
168
nppid=transdl$prod=="MOD17"
169

  
170
xyplot(value~dist|transect,groups=prod,type=c("smooth","p"),
171
       data=transdl,panel=function(...,subscripts=subscripts) {
172
         td=transdl[subscripts,]
256
  ))
257

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

  
260
#rondonia=trd[trd$trans=="Brazil",]
261
#trd=trd[trd$trans!="Brazil",]
262

  
263
at=seq(0,100,leng=100)
264
bgyr=colorRampPalette(c("purple","blue","green","yellow","orange","red","red"))
265
bgrayr=colorRampPalette(c("purple","blue","grey","red","red"))
266
cols=bgyr(100)
267

  
268
## global map
269
library(maptools)
270
coast=map2SpatialLines(map("world", interior=FALSE, plot=FALSE),proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
271

  
272
g1=levelplot(stack(mod35c5,mod35c6,mod09),xlab=" ",scales=list(x=list(draw=F),y=list(alternating=1)),col.regions=cols,at=at)+layer(sp.polygons(bbs[1:4],lwd=2))+layer(sp.lines(coast,lwd=.5))
273
#g2=levelplot(dif,col.regions=bgrayr(100),at=seq(-70,70,len=100),margin=F,ylab=" ",colorkey=list("right"))+layer(sp.polygons(bbs[1:4],lwd=2))+layer(sp.lines(coast,lwd=.5))
274
#trellis.par.set(background=list(fill="white"),panel.background=list(fill="white"))
275
#g3=histogram(dif,bg="white",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))
276

  
277
### regional plots
278
p1=useOuterStrips(levelplot(value~x*y|variable+trans,data=trd[!trd$variable%in%c("MCD12Q1","MOD35pp"),],asp=1,scales=list(draw=F,rot=0,relation="free"),
279
                                       at=at,col.regions=cols,maxpixels=7e6,
280
                                       ylab="Latitude",xlab="Longitude"),strip = strip.custom(par.strip.text=list(cex=.75)))+layer(sp.lines(trans,lwd=2))
281

  
282
p2=useOuterStrips(
283
  levelplot(value~x*y|variable+trans,data=trd[trd$variable%in%c("MCD12Q1"),],
284
            asp=1,scales=list(draw=F,rot=0,relation="free"),colorkey=F,
285
            at=c(-1,IGBP$ID),col.regions=IGBP$col,maxpixels=7e7,
286
            legend=list(
287
              right=list(fun=draw.key(list(columns=1,#title="MCD12Q1 \n IGBP Land \n Cover",
288
                           rectangles=list(col=IGBP$col,size=1),
289
                           text=list(as.character(IGBP$ID),at=IGBP$ID-.5))))),
290
            ylab="",xlab=" "),strip = strip.custom(par.strip.text=list(cex=.75)),strip.left=F)+layer(sp.lines(trans,lwd=2))
291
p3=useOuterStrips(
292
  levelplot(value~x*y|variable+trans,data=trd[trd$variable%in%c("MOD35pp"),],
293
            asp=1,scales=list(draw=F,rot=0,relation="free"),colorkey=F,
294
            at=c(-1:4),col.regions=c("blue","cyan","tan","darkgreen"),maxpixels=7e7,
295
            legend=list(
296
              right=list(fun=draw.key(list(columns=1,#title="MOD35 \n Processing \n Path",
297
                           rectangles=list(col=c("blue","cyan","tan","darkgreen"),size=1),
298
                           text=list(c("Water","Coast","Desert","Land")))))),
299
            ylab="",xlab=" "),strip = strip.custom(par.strip.text=list(cex=.75)),strip.left=F)+layer(sp.lines(trans,lwd=2))
300

  
301
## transects
302
p4=xyplot(value~dist|transect,groups=variable,type=c("smooth","p"),
303
       data=transd,panel=function(...,subscripts=subscripts) {
304
         td=transd[subscripts,]
173 305
         ## mod09
174
         imod09=td$prod=="MOD09_cloud"
175
         panel.xyplot(td$dist[imod09],td$value[imod09],type=c("p","smooth"),span=0.2,subscripts=1:sum(imod09),col="red",pch=16,cex=.5)
306
         imod09=td$variable=="MOD09CF"
307
         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)
176 308
         ## mod35C5
177
         imod35=td$prod=="MOD35C5_cloud"
178
         panel.xyplot(td$dist[imod35],td$value[imod35],type=c("p","smooth"),span=0.09,subscripts=1:sum(imod35),col="blue",pch=16,cex=.5)
309
         imod35=td$variable=="C5MOD35CF"
310
         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)
311
         ## mod35C6
312
         imod35c6=td$variable=="C6MOD35CF"
313
         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)
179 314
         ## mod17
180
         imod17=td$prod=="MOD17"
181
         panel.xyplot(td$dist[imod17],100*td$value[imod17]/max(td$value[imod17]),
182
                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="darkgreen",lty="dashed",pch=1,cex=.5)
183
         imod17qc=td$prod=="MOD17qc"
184
         panel.xyplot(td$dist[imod17qc],td$value[imod17qc],type=c("p","smooth"),span=0.09,subscripts=1:sum(imod17qc),col="darkgreen",pch=16,cex=.5)
315
         imod17=td$variable=="MOD17"
316
         panel.xyplot(td$dist[imod17],100*((td$value[imod17]-td$min[imod17][1])/(td$max[imod17][1]-td$min[imod17][1])),
317
                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="darkgreen",lty=5,pch=1,cex=.25)
318
         imod17qc=td$variable=="MOD17CF"
319
         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)
185 320
         ## mod11
186
#         imod11=td$prod=="MOD11"
187
#         panel.xyplot(td$dist[imod17],100*td$value[imod17]/max(td$value[imod17]),
188
#                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="darkgreen",lty="dashed",pch=1,cex=.5)
189
         imod11qc=td$prod=="MOD11qc"
190
         panel.xyplot(td$dist[imod11qc],td$value[imod11qc],type=c("p","smooth"),span=0.09,subscripts=1:sum(imod11qc),col="maroon",pch=16,cex=.5)
191
         ## means
192
         means=td$prod%in%c("","MOD17qc","MOD09_cloud","MOD35_cloud")
321
         imod11=td$variable=="MOD11"
322
         panel.xyplot(td$dist[imod11],100*((td$value[imod11]-td$min[imod11][1])/(td$max[imod11][1]-td$min[imod11][1])),
323
                      type=c("smooth"),span=0.09,subscripts=1:sum(imod17),col="orange",lty="dashed",pch=1,cex=.25)
324
         imod11qc=td$variable=="MOD11CF"
325
         qcspan=ifelse(td$transect[1]=="Australia",0.2,0.05)
326
         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)
193 327
         ## land
194
         path=td[td$prod=="MOD35_ProcessPath",]
195
         panel.segments(path$dist,0,c(path$dist[-1],max(path$dist)),0,col=IGBP$col[path$value],subscripts=1:nrow(path),lwd=15,type="l")
196
         land=td[td$prod=="MCD12Q1",]
197
         panel.segments(land$dist,-5,c(land$dist[-1],max(land$dist)),-5,col=IGBP$col[land$value],subscripts=1:nrow(land),lwd=15,type="l")
198
       },subscripts=T,par.settings = list(grid.pars = list(lineend = "butt")),
328
         path=td[td$variable=="MOD35pp",]
329
         panel.segments(path$dist,-5,c(path$dist[-1],max(path$dist,na.rm=T)),-5,col=c("blue","cyan","tan","darkgreen")[path$value+1],subscripts=1:nrow(path),lwd=15,type="l")
330
         land=td[td$variable=="MCD12Q1",]
331
         panel.segments(land$dist,-10,c(land$dist[-1],max(land$dist,na.rm=T)),-10,col=IGBP$col[land$value+1],subscripts=1:nrow(land),lwd=15,type="l")
332
        },subscripts=T,par.settings = list(grid.pars = list(lineend = "butt")),
199 333
       scales=list(
200
         x=list(alternating=1), #lim=c(0,50),
201
         y=list(at=c(-5,0,seq(20,100,len=5)),
202
           labels=c("IGBP","MOD35",seq(20,100,len=5)),
203
           lim=c(-10,100))),
204
       xlab="Distance Along Transect (km)", 
205
       key=list(space="right",lines=list(col=c("red","blue","darkgreen","maroon")),text=list(c("MOD09 % Cloudy","MOD35 % Cloudy","MOD17 % Missing","MOD11 % Missing"),lwd=1,col=c("red","blue","darkgreen","maroon"))))
206

  
334
         x=list(alternating=1,relation="free"),#, lim=c(0,70)),
335
         y=list(at=c(-10,-5,seq(0,100,len=5)),
336
           labels=c("IGBP","MOD35",seq(0,100,len=5)),
337
           lim=c(-15,100))),
338
       xlab="Distance Along Transect (km)", ylab="% Missing Data / % of Maximum Value",
339
       legend=list(
340
         #inside=list(fun=draw.key(list(
341
         #                        lines=list(type="b",pch=16,cex=.5,lty=c(1,1,1,5,1,5),col=c("red","blue","darkgreen","darkgreen","orange","orange")),
342
         #                        text=list(c("MOD09 % Cloudy","MOD35 % Cloudy","MOD17 % Missing","MOD17 (scaled)","MOD11 % Missing","MOD11 (scaled)"),
343
         #       lwd=1,col=c("red","blue","darkgreen","darkgreen","orange","orange")))),corner=c(1,.34)) ,
344
        right=list(fun=draw.key(list(columns=1,#title="MCD12Q1",
345
                   lines=list(type=c("b","b","b","b","l","b","l"),pch=16,cex=.5,lty=c(1,1,1,1,5,1,5),col=c("red","blue","black","darkgreen","darkgreen","orange","orange",rep(NA,12))),
346
                     rectangles=list(border=NA,col=c(rep(NA,8),"tan","darkgreen",NA,IGBP$col[sort(unique(transd$value[transd$variable=="MCD12Q1"]+1))]) ),
347
                         text=list(c("MOD09 % Cloudy","C5 MOD35 % Cloudy","C6 MOD35 % Cloudy","MOD17 % Missing","MOD17 (scaled)","MOD11 % Missing","MOD11 (scaled)",
348
                           "\n \n \n C5 MOD35 Processing Path","Desert","Land","\n \n \n MCD12Q1 IGBP Land Cover",IGBP$class[sort(unique(transd$value[transd$variable=="MCD12Q1"]+1))])))))),
349
         strip = strip.custom(par.strip.text=list(cex=.75)))
350
#
351
print(p4)
352

  
353
#p5=levelplot(value~x*y|variable,data=rondonia,asp=1,scales=list(draw=F,rot=0,relation="free"),colorkey=T)#,
354
#print(p5)
355

  
356

  
357
CairoPDF("output/mod35compare.pdf",width=11,height=7)
358
#CairoPNG("output/mod35compare_%d.png",units="in", width=11,height=8.5,pointsize=4000,dpi=1200,antialias="subpixel")
359
### Global Comparison
360
print(g1)
361
#print(g1,position=c(0,.33,1,1),more=T)
362
#print(g2,position=c(0,0,1,0.394),more=T)
363
#print(g3,position=c(0.31,0.06,.42,0.27),more=F)
364
### MOD35 Desert Processing path
365
levelplot(pp,asp=1,scales=list(draw=T,rot=0),maxpixels=1e6,
366
          at=c(-1:3),col.regions=c("blue","cyan","tan","darkgreen"),margin=F,
367
          colorkey=list(space="bottom",title="MOD35 Processing Path",labels=list(labels=c("Water","Coast","Desert","Land"),at=0:4-.5)))+layer(sp.polygons(bbs,lwd=2))+layer(sp.lines(coast,lwd=.5))
207 368
### levelplot of regions
369
print(p1,position=c(0,0,.62,1),more=T)
370
print(p2,position=c(0.6,0.21,0.78,0.79),more=T)
371
print(p3,position=c(0.76,0.21,1,0.79))
372
### profile plots
373
print(p4)
374
dev.off()
208 375

  
376
### summary stats for paper
377
  td=cast(transect+loc+dist~variable,value="value",data=transd)
378
  td2=melt.data.frame(td,id.vars=c("transect","dist","loc","MOD35pp","MCD12Q1"))
209 379

  
210
c(levelplot(mod35c5,margin=F),levelplot(mod09,margin=F),levelplot(mod11qc),levelplot(mod17qc),x.same = T, y.same = T)
380
## function to prettyprint mean/sd's
381
msd= function(x) paste(round(mean(x,na.rm=T),1),"% ±",round(sd(x,na.rm=T),1),sep="")
211 382

  
212
levelplot(modprod)
383
cast(td2,transect+variable~MOD35pp,value="value",fun=msd)
384
cast(td2,transect+variable~MOD35pp+MCD12Q1,value="value",fun=msd)
385
cast(td2,transect+variable~.,value="value",fun=msd)
386

  
387
cast(td2,transect+variable~.,value="value",fun=msd)
388

  
389
cast(td2,variable~MOD35pp,value="value",fun=msd)
390
cast(td2,variable~.,value="value",fun=msd)
391

  
392
td[td$transect=="Venezuela",]
213 393

  
214 394

  
215 395

  
216
### LANDCOVER
217
levelplot(lulcf,col.regions=levels(lulcf)[[1]]$col,
218
          scales=list(cex=2),
219
          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)
220 396

  
397
## scatterplot of MOD35 vs MOD09
398
trdl=cast(trans+x+y~variable,value="value",data=trd)
399
xyplot(MOD35C5qc~MOD09qc|trans+as.factor(MOD35pp),pch=16,cex=.2,data=trdl,auto.key=T)+layer(panel.abline(0,1))
400

  
401

  
402
### LANDCOVER
403
levelplot(lulc,col.regions=IGBP$col,scales=list(cex=2),colorkey=list(space="right",at=0:17,labels=list(at=seq(0.5,16.5,by=1),labels=levels(lulc)[[1]]$class,cex=2)),margin=F)
221 404

  
222 405
levelplot(mcompare,col.regions=cols,at=at,margin=F,sub="Frequency of MOD35 Clouds in March")
223 406
#levelplot(dif,col.regions=bgyr(20),margin=F)
climate/procedures/MOD35_ExtractProcessPath.r
65 65
   outfile=paste("~/acrobates/adamw/projects/interp/data/modis/mod35/gridded/",bfile,".tif",sep="")  #final file
66 66
   if(file.exists(outfile)) return(c(file,0))
67 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
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
75 76
   ## First write the parameter file (careful, heg is very finicky!)
76 77
   hdr=paste("NUM_RUNS = ",length(vars$varid),"|MULTI_BAND_HDFEOS:",length(vars$varid),sep="")
77 78
   grp=paste("
......
183 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"))
184 185

  
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

  
186 190
#  origin(raster(gfiles[5]))
187 191
  
188 192
  ## try with pktools
189 193
  ## global
190
system(paste("pkmosaic -co COMPRESS=LZW -co PREDICTOR=2 ",paste("-i",list.files("gridded",full=T,pattern="tif$"),collapse=" ")," -o MOD35_path_pkmosaic_max.tif  -m 2 -v -t 255 -t 0 &"))
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 &"))
191 195
#bb="-ulx -180 -uly 90 -lrx 180 -lry -90"
192 196
#bb="-ulx -180 -uly 90 -lrx 170 -lry 80"
193 197
bb="-ulx -72 -uly 11 -lrx -59 -lry -1"
......
239 243
cols=c("blue","lightblue","tan","green")
240 244

  
241 245

  
242
  ###  Merge them into a geotiff
243
    system(paste("gdal_merge.py -v -n 255 -o MOD35_ProcessPath.tif -co \"COMPRESS=LZW\" -co \"PREDICTOR=2\" `ls -d -1 gridded/*.tif`",sep=""))
244

  
245 246

  
246 247
## connect to raster to extract land-cover bit
247 248
library(raster)
climate/procedures/StationGapAnalysis.R
1

  
2
setwd("~/acrobates/adamw/projects/interp/data")
3
library(reshape)
4
library(sp);library(rgdal);
5
library(reshape)
6
library(ncdf4)
7
library(geosphere)
8
library(rgeos)
9
library(multicore);library(RSQLite)
10

  
11
stInfo=function(file,inventory,vars=vars){
12
  ### read in station location data
13
    cs=c(11,-1,8,-1,9,-1,6,-4,30,-1,3,-1,3,-1,5) #column widths, negative means skip
14
      print("Importing station data")
15
      st=read.fwf(file,widths=cs,colClasses="character",comment.char = "",header=F,skip=0)
16
      colnames(st)=c("id","lat","lon","elev","name","gsnflag","hcnflag","wmoid")
17
      print("Updating factors")
18
      for(i in c(5,6,7,8)) st[,i]=as.factor(st[,i])
19
      for(i in 2:4) st[,i]=as.numeric(st[,i])
20
    ### inventory
21
      print("Getting station start-stop years from station inventory file")
22
      cs=c(11,-1,8,-1,9,-1,4,-1,4,-1,4) #column widths, negative means skip
23
      stinv=read.fwf(inventory,widths=cs,colClasses="character",comment.char = "",header=F,skip=0)
24
      colnames(stinv)=c("id","lat","lon","variable","yearstart","yearstop")
25
      stinv=stinv[stinv$variable%in%vars,]
26
    ### reshape yearstart
27
      stinvw1=cast(stinv,id+lat+lon~variable,value="yearstart")
28
      colnames(stinvw1)[!grepl("id|lat|lon",colnames(stinvw1))]=
29
            paste(colnames(stinvw1)[!grepl("id|lat|lon",colnames(stinvw1))],".start",sep="")
30
    ### reshape yearstop
31
      stinvw2=cast(stinv,id+lat+lon~variable,value="yearstop")
32
      colnames(stinvw2)[!grepl("id|lat|lon",colnames(stinvw2))]=
33
            paste(colnames(stinvw2)[!grepl("id|lat|lon",colnames(stinvw2))],".stop",sep="")
34
      stinvw=merge(stinvw1,stinvw2)
35
      for(i in colnames(stinvw[,!grepl("id|lat|lon",colnames(stinvw))])) stinvw[,i]=as.numeric(as.character( stinvw[,i]))
36
      colnames(stinvw)=sub("TMAX","tmax",colnames(stinvw))
37
      colnames(stinvw)=sub("TMIN","tmin",colnames(stinvw))
38
      colnames(stinvw)=sub("PRCP","ppt",colnames(stinvw))
39
    ### merge the data
40
      print("Merging start-stop dates with station locations")
41
      st2=merge(st,stinvw[,!grepl("lat|lon",colnames(stinvw))],all.x=T,by=c("id"))
42
    ## add station type field
43
    st2$type=ifelse((!is.na(st2$tmax.start)|!is.na(st2$tmin.start))&!is.na(st2$ppt.start),"T&P",
44
      ifelse((!is.na(st2$tmax.start)|!is.na(st2$tmin.start))&is.na(st2$ppt.start),"T",
45
             ifelse((is.na(st2$tmax.start)|is.na(st2$tmin.start))&!is.na(st2$ppt.start),"P","None")))
46
    ### Convert to spatial points and return
47
      print("Convert to spatial points")
48
      coordinates(st2)=c("lon","lat")
49
      st2@data[,c("lon","lat")]=coordinates(st2)
50
      proj4string(st2)=CRS("+proj=longlat +datum=WGS84")
51
      return(st2)
52
  }
53

  
54

  
55
### Process the station data
56
st=stInfo(file="ghcn/ghcnd-stations.txt",inventory="ghcn/ghcnd-inventory.txt",
57
    vars=c("PRCP","TMAX","TMIN"))
58

  
59
writeOGR(st,".","stationlocations",driver="ESRI Shapefile",overwrite=T)

Also available in: Unified diff