Project

General

Profile

Download (22.2 KB) Statistics
| Branch: | Revision:
1
library(sp)                                                                                                                                                                          
2
library(spgrass6)                                                                                                                                                                    
3
library(rgdal)                                                                                                                                                                       
4
library(reshape)                                                                                                                                                                     
5
library(ncdf4)                                                                                                                                                                       
6
library(geosphere)                                                                                                                                                                   
7
library(rgeos)                                                                                                                                                                       
8
library(multicore)                                                                                                                                                                   
9
library(raster)                                                                                                                                                                      
10
library(lattice)                                                                                                                                                                     
11
library(rgl)                                                                                                                                                                         
12
library(hdf5)                                                                                                                                                                        
13
library(rasterVis)                                                                                                                                                                   
14
library(heR.Misc)
15
library(spBayes)
16
library(xtable)
17
library(ellipse) # for correlation matrix
18
library(maptools) # for rgshhs
19

    
20
X11.options(type="X11")
21

    
22
ncores=20  #number of threads to use
23

    
24

    
25
### copy lulc data to litoria
26
#setwd("data/lulc")
27
#system("scp atlas:/home/parmentier/data_Oregon_stations/W_Layer* .")
28

    
29

    
30
setwd("/home/adamw/acrobates/projects/interp")       
31

    
32
projs=CRS("+proj=lcc +lat_1=43 +lat_2=45.5 +lat_0=41.75 +lon_0=-120.5 +x_0=400000 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs")
33
months=format(ISOdate(2004,1:12,1),"%b")
34

    
35
### load station data, subset to stations in region, and transform to sinusoidal
36
load("data/ghcn/roi_ghcn.Rdata")
37
load("data/allstations.Rdata")
38

    
39
d2=d[d$variable=="tmax"&d$date>=as.Date("2000-01-01"),]
40
d2=d2[,-grep("variable",colnames(d2)),]
41
st2=st[st$id%in%d$id,]
42
st2=spTransform(st2,projs)
43
d2[,c("lon","lat")]=coordinates(st2)[match(d2$id,st2$id),]
44
d2$elev=st2$elev[match(d2$id,st2$id)]
45
d2$month=format(d2$date,"%m")
46
d2$value=d2$value/10 #convert to mm
47

    
48

    
49
## load topographical data
50
topo=brick(as.list(list.files("data/regions/oregon/topo",pattern="SRTM.*rst$",full=T)))
51
topo=calc(topo,function(x) ifelse(x<0,NA,x))
52
names(topo)=c("aspect","dem","slope")
53
colnames(topo@data@values)=c("aspect","dem","slope")
54
projection(topo)=projs
55
NS=sin(subset(topo,subset="slope")*pi/180)*cos(subset(topo,subset="aspect")*pi/180);names(NS)="northsouth"
56
EW=sin(subset(topo,subset="slope")*pi/180)*sin(subset(topo,subset="aspect")*pi/180);names(EW)="eastwest"
57
slope=sin(subset(topo,subset="slope")*pi/180);names(slope)="slope"
58

    
59
## load coastline data
60
roill=bbox(projectExtent(topo,CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")))
61
coast=getRgshhsMap("/home/adamw/acrobates/Global/GSHHS_shp/gshhs/gshhs_f.b",xlim=c(roill[1,1],roill[1,2]),ylim=c(roill[2,1],roill[2,2]))
62
coast=as(as(coast,"SpatialLines"),"SpatialLinesDataFrame")
63
coast@data=data.frame(id=1:length(coast@lines))  #convert to dataframe
64
coast=spTransform(coast,projs)
65
rcoast=rasterize(coast,topo)
66
dist=distance(rcoast)/1000 #get distance to coast and convert to km
67
### transform distance to coast using b-log(dist), where b \approx log(DTC of the farthest point on earth from the sea)
68
### Garcia-Castellanos, Daniel, and Umberto Lombardo. 2007. “Poles of Inaccessibility: A Calculation Algorithm for the Remotest Places on Earth.” Scottish Geographical Journal 123 (3): 227–233. doi:10.1080/14702540801897809.
69
### farthest point is ~2510km from ocean
70
log(2510) #round up to 8 to be sure we won't get negative numbers
71
dist2=brick(dist,calc(dist,function(x) (8-log(x+1))))
72
layerNames(dist2)=c("DTCkm","logDTCkm")
73
colnames(dist2@data@values)=c("DTCkm","logDTCkm")
74
topo2=stack(subset(topo,"dem"),EW,NS,slope,dist2)
75

    
76
## create binned elevation for stratified sampling
77
demc=quantile(subset(topo,subset="dem"))
78
demb=calc(subset(topo,subset="dem"),function(x) as.numeric(cut(x,breaks=demc)))
79
names(demb)="demb"
80
##topo=brick(list(topo,demb))
81

    
82

    
83
### load the lulc data as a brick
84
lulc=brick(as.list(list.files("data/regions/oregon/lulc",pattern="rst$",full=T)))
85
#projection(lulc)=
86
#plot(lulc)
87

    
88
## Enter lulc types (from Nakaegawa 2011)
89
lulct=as.data.frame(matrix(c(
90
  "Forest",1,
91
  "Shrub",2,
92
  "Grass",3,
93
  "Crop",4,
94
  "Mosaic",5,
95
  "Urban",6,
96
  "Barren",7,
97
  "Snow",8,
98
  "Wetland",9,
99
  "Water",10),byrow=T,ncol=2,dimnames=list(1:10,c("class","id"))),stringsAsFactors=F)
100
colnames(lulc@data@values)=lulct$class[as.numeric(gsub("[a-z]|[A-Z]|[_]|83","",layerNames(lulc)))]
101
layerNames(lulc)=lulct$class[as.numeric(gsub("[a-z]|[A-Z]|[_]|83","",layerNames(lulc)))]
102
lulc=calc(lulc,function(x) ifelse(is.na(x),0,x))
103
projection(lulc)=projs
104

    
105
### reclass/sum classes
106
ShrubGrass=subset(lulc,"Shrub")+subset(lulc,"Grass");layerNames(ShrubGrass)="ShrubGrass"
107
Other=subset(lulc,"Mosaic")+subset(lulc,"Barren")+subset(lulc,"Snow")+subset(lulc,"Wetland");layerNames(Other)="Other"
108
lulc2=stack(subset(lulc,"Forest"),subset(lulc,"Urban"),subset(lulc,"Crop"),Other,ShrubGrass)
109

    
110
### load the LST data
111
lst=brick(as.list(list.files("data/regions/oregon/lst",pattern="rescaled.rst$",full=T)[c(4:12,1:3)]))
112
lst=lst-273.15
113
colnames(lst@data@values)=format(as.Date(paste("2000-",as.numeric(gsub("[a-z]|[A-Z]|[_]|83","",layerNames(lst))),"-15",sep="")),"%b")
114
layerNames(lst)=format(as.Date(paste("2000-",as.numeric(gsub("[a-z]|[A-Z]|[_]|83","",layerNames(lst))),"-15",sep="")),"%b")
115
projection(lst)=projs
116

    
117

    
118
######################################
119
## compare LULC with station data
120
st2=st2[!is.na(extract(demb,st2)),]
121
st2=SpatialPointsDataFrame(st2,data=cbind.data.frame(st2@data,demb=extract(demb,st2),extract(topo,st2),extract(topo2,st2),extract(lulc2,st2,buffer=1500,fun=mean),extract(lst,st2)))
122
stlulc=extract(lulc2,st2,buffer=1500,fun=mean) #overlay stations and LULC values
123
st2$lulc=do.call(c,lapply(apply(stlulc,1,function(x) which.max(x)),function(x) ifelse(is.null(names(x)),NA,names(x))))
124

    
125

    
126
###  add MODIS metric to station data for month corresponding to that date
127
### reshape for easy merging
128
sdata.ul=melt(st2@data,id.vars=c("id","lat","lon","Forest","ShrubGrass","Crop","Urban","Other","lulc"),measure.vars=format(as.Date(paste("2000-",1:12,"-15",sep="")),"%b"))
129

    
130
### generate sample of points to speed processing
131
n=10000/length(unique(demb))
132
n2=30  #number of knots
133
s=sampleStratified(demb,size=n,sp=T)
134
#s=spsample(as(topo,"SpatialGrid"),n=n,type="regular")
135
s2=spsample(as(topo,"SpatialGrid"),n=n2,type="regular")
136

    
137
         
138
s=SpatialPointsDataFrame(s,data=cbind.data.frame(x=coordinates(s)[,1],y=coordinates(s)[,2],demb=extract(demb,s),extract(topo,s),extract(topo2,s),extract(lulc,s),extract(lst,s)))
139
### drop areas with no LST data
140
#s=s[!is.na(s$Aug),]
141
s=s[apply(s@data,1,function(x) all(!is.na(x))),]
142

    
143
###  add majority rules lulc for exploration
144
s$lulc=apply(s@data[,colnames(s@data)%in%lulct$class],1,function(x) (colnames(s@data)[colnames(s@data)%in%lulct$class])[which.max(x)])
145
save(s,file=paste("output/mod_sample.Rdata",sep=""))
146

    
147

    
148
### spatial regression to fit lulc coefficients
149
Sys.setenv(MKL_NUM_THREADS=24)
150
system("export MKL_NUM_THREADS=24")
151

    
152
niter=12500
153
lapply(months,function(m){
154
  print(paste("###################################   Starting month ",m))
155
  f1=formula(paste(m,"~logDTCkm+y+Shrub+Grass+Crop+Mosaic+Urban+Barren+Snow+Wetland+dem+eastwest+northsouth",sep=""))
156
  m1=spLM(f1,data=s@data,coords=coordinates(s),knots=coordinates(s2),
157
    starting=list("phi"=0.6,"sigma.sq"=1, "tau.sq"=1),
158
    sp.tuning=list("phi"=0.01, "sigma.sq"=0.05, "tau.sq"=0.05),
159
    priors=list("phi.Unif"=c(0.3, 3), "sigma.sq.IG"=c(2, 1), "tau.sq.IG"=c(2, 1)),
160
    cov.model="exponential",
161
    n.samples=niter,sub.samples=c(2500,niter,10),verbose=TRUE, n.report=100)
162
  assign(paste("mod_",m,sep=""),m1)
163
  save(list=paste("mod_",m,sep=""),file=paste("output/mod_",m,".Rdata",sep=""))
164
})
165

    
166
### Read in results
167
load(paste("output/mod_sample.Rdata",sep=""))
168
ms=lapply(months,function(m) {print(m); load(paste("output/mod_",m,".Rdata",sep="")) ; get(paste("mod_",m,sep="")) })
169

    
170
### generate summaries
171
ms1=do.call(rbind.data.frame,lapply(1:length(ms),function(i){
172
  mi=ms[[i]]
173
  m1.s=mcmc(t(mi$p.samples),start=round(niter/4),thin=1)
174
  m1.s2=as.data.frame(t(apply(m1.s,1,quantile,c(0.025,0.5,0.975))))
175
  colnames(m1.s2)=c("Q2.5","Q50","Q97.5")
176
  m1.s2$parm=rownames(m1.s)
177
  m1.s2$month=factor(months[i],levels=months,ordered=T)
178
  m1.s2$type=ifelse(m1.s2$parm%in%c("tau.sq","sigma.sq","phi"),"Spatial",ifelse(m1.s2$parm%in%c("(Intercept)","eastwest","northsouth","dem","logDTCkm","y"),"Topography","LULC"))
179
  return(m1.s2)
180
}))
181
## drop spatial parameters
182
#ms1=ms1[!ms1$type%in%"Spatial",]
183
## Convert dem to degrees/km to make it comparable to other topographical parameters
184
#ms1[ms1$parm%in%c("x","y","dem"),c("Q2.5","Q50","Q97.5")]=ms1[ms1$parm%in%c("x","y","dem"),c("Q2.5","Q50","Q97.5")]
185

    
186

    
187
#######################################################################
188
#### look at interaction of tmax~lst*lulc using monthly means
189
### add monthly data to sdata table by matching unique station_month ids.
190
d2$month=as.numeric(format(d2$date,"%m"))
191
### get monthly means and sd's
192
dm=melt(cast(d2,id+lon+lat+elev~month,value="value",fun.aggregate=mean,na.rm=T),id.vars=c("id","lon","lat","elev"));colnames(dm)[grep("value",colnames(dm))]="mean"
193
ds=melt(cast(d2,id+lon+lat+elev~month,value="value",fun.aggregate=sd,na.rm=T),id.vars=c("id","lon","lat","elev"))  #sd of tmax
194
dn=melt(cast(d2,id+lon+lat+elev~month,value="value",fun.aggregate=length),id.vars=c("id","lon","lat","elev"))  #number of observations
195
dm$sd=ds$value
196
dm$n=dn$value[match(paste(dm$month,dm$id),paste(dn$month,dn$id))]/max(dn$value)  # % complete record
197

    
198
#get lulc classes
199
lcs=layerNames(lulc2)
200

    
201
dm$lst=sdata.ul$value[match(paste(dm$id,format(as.Date(paste("2000-",dm$month,"-15",sep=""),"%Y-%m-%d"),"%b"),sep="_"),paste(sdata.ul$id,sdata.ul$variable,sep="_"))]
202
dm[,lcs]=sdata.ul[match(dm$id,sdata.ul$id),lcs]
203
dm=dm[!is.na(dm$ShrubGrass),]
204
dm$class=lcs[apply(dm[,lcs],1,which.max)]
205
## update month names
206
dm$m2=format(as.Date(paste("2000-",dm$month,"-15",sep="")),"%B")
207
dm$m2=factor(as.character(dm$m2),levels=format(as.Date(paste("2000-",1:12,"-15",sep="")),"%B"),ordered=T)
208

    
209
xyplot(mean~lst|m2,groups=class,data=dm,panel=function(x,y,subscripts,groups){  #+cut(dm$elev,breaks=quantile(dm$elev,seq(0,1,len=4)),labels=c("low","medium","high"))
210
  dt=dm[subscripts,]
211
  #panel.segments(dt$lst,dt$mean-dt$sd,dt$lst,dt$mean+dt$sd,groups=groups,lwd=.5,col="#C1CDCD")
212
  panel.xyplot(dt$lst,dt$mean,groups=groups,subscripts=subscripts,type=c("p","r"),cex=0.5)
213
  panel.abline(0,1,col="black",lwd=2)
214
},par.settings = list(superpose.symbol = list(pch=1:6,col=c("lightgreen","darkgreen","grey","brown","red"))),
215
       auto.key=list(space="right"),scales=list(relation="free"),
216
       sub="Each point represents a monthly mean (climatology) for a single station \n Points are colored by LULC class with largest % \n Heavy black line is y=x",main="Monthly Mean LST and Monthly Mean Tmax",
217
       ylab="Mean Monthly Tmax (C)",xlab="Mean Monthly LST")
218

    
219

    
220
mods=data.frame(
221
  form=c(
222
    "mean~lst+elev",
223
    "mean~lst+elev+ShrubGrass+Urban+Crop+Other",
224
    "mean~lst+elev+lst*ShrubGrass+lst*Urban+lst*Crop+lst*Other"
225
    ),
226
  type=c("lst","intercept","interact"),
227
  stringsAsFactors=F)
228
mods2=expand.grid(form=mods$form,month=1:12)
229
mods2$type=mods$type[match(mods2$form,mods$form)]
230

    
231

    
232
#summary(lm(mods$form[4],data=dm,weight=dm$n))
233

    
234
ms=lapply(1:nrow(mods2),function(i) {
235
  m=lm(as.formula(as.character(mods2$form[i])),data=dm[dm$month==mods2$month[i],],weight=dm$n[dm$month==mods2$month[i]])
236
  return(list(model=m,
237
              res=data.frame(
238
                Formula=as.character(mods2$form[i]),
239
                Month=mods2$month[i],
240
                type=mods2$type[i],
241
                AIC=AIC(m),
242
                R2=summary(m)$r.squared)))
243
})
244

    
245
### identify lowest AIC per month
246
ms1=do.call(rbind.data.frame,lapply(ms,function(m) m$res))
247
aicw= cast(ms1,Month~type,value="AIC")
248
aicwt=as.data.frame(t(apply(aicw[,-1],1,function(x) ifelse(x==min(x),"Minimum",ifelse((x-min(x))<7,"NS Minimum","NS")))));colnames(aicwt)=colnames(aicw)[-1];aicwt$Month=aicw$Month
249
aic=melt(aicwt,id.vars="Month");colnames(aic)=c("Month","type","minAIC")
250
aic$minAIC=factor(aic$minAIC,ordered=F)
251

    
252
xyplot(AIC~as.factor(Month),groups=Formula,data=ms1,type=c("p","l"),pch=16,auto.key=list(space="top"),main="Model Comparison across months",
253
       par.settings = list(superpose.symbol = list(pch=16,cex=1)),xlab="Month")
254

    
255

    
256
ms2=lapply(ms,function(m) m$model)
257

    
258
mi=rep(c(1:12),each=3)  #month indices
259

    
260
fs=do.call(rbind.data.frame,lapply(1:12,function(i){
261
  it=which(mi==i)
262
  x=anova(ms2[[it[1]]],ms2[[it[2]]],ms2[[it[3]]])
263
  fs=c(
264
    paste(as.character(formula(ms2[[it[1]]]))[c(2,1,3)],collapse=" "),
265
    paste(as.character(formula(ms2[[it[2]]]))[c(2,1,3)],collapse=" "),
266
    paste(as.character(formula(ms2[[it[3]]]))[c(2,1,3)],collapse=" "))
267
  data.frame(month=rep(i,3),model=fs,p=as.data.frame(x)[,6],sig=ifelse(as.data.frame(x)[,6]<0.05,T,F))
268
}))
269

    
270
table(fs$sig,fs$model)
271
which(fs$sig)
272

    
273
### load oregon boundary for comparison
274
roi=spTransform(as(readOGR("data/regions/Test_sites/Oregon.shp","Oregon"),"SpatialLines"),projs)
275

    
276

    
277
bgyr=colorRampPalette(c("blue","green","yellow","red"))
278
pdf("output/lst_lulc.pdf",width=11,height=8.5)
279

    
280
### Summary plots of covariates
281
## LULC
282
at=seq(0.1,100,length=100)
283
levelplot(lulc2,at=at,col.regions=bgyr(length(at)),
284
          main="Land Cover Classes",sub="Sub-pixel %")+
285
  layer(sp.lines(roi, lwd=1.2, col='black'))
286

    
287
## TOPO
288
at=unique(quantile(as.matrix(subset(topo2,c("eastwest","northsouth","slope"))),seq(0,1,length=100),na.rm=T))
289
levelplot(subset(topo2,c("eastwest","northsouth","slope")),at=at,col.regions=bgyr(length(at)),
290
          main="Topographic Variables",sub="")+
291
  layer(sp.lines(roi, lwd=1.2, col='black'))
292

    
293

    
294
## DEM
295
at=unique(quantile(as.matrix(subset(topo2,c("dem"))),seq(0,1,length=100),na.rm=T))
296
levelplot(subset(topo2,c("dem")),at=at,col.regions=bgyr(length(at)),
297
          main="Elevation",sub="",margin=F)+
298
  layer(sp.lines(roi, lwd=1.2, col='black'))
299

    
300
## DTC
301
at=unique(quantile(as.matrix(subset(topo2,c("logDTCkm"))),seq(0,1,length=100),na.rm=T))
302
levelplot(subset(topo2,c("logDTCkm")),at=at,col.regions=bgyr(length(at)),
303
          main="Elevation",sub="",margin=F)+
304
  layer(sp.lines(roi, lwd=1.2, col='black'))
305

    
306
#LST
307
at=quantile(as.matrix(lst),seq(0,1,length=100),na.rm=T)
308
levelplot(lst,at=at,col.regions=bgyr(length(at)),
309
                      main="MOD11A1 Mean Monthly LST")+
310
  layer(sp.lines(roi, lwd=1.2, col='black'))
311

    
312

    
313
xyplot(value~dem|variable,groups=lulc,melt(s@data[,c("dem","lulc",months)],id.vars=c("dem","lulc")),pch=16,cex=.5,
314
       main="Month-by-month scatterplots of Elevation and LST, grouped by LULC",
315
       sub="One point per pixel, per month",ylab="LST",
316
       par.settings = list(superpose.symbol = list(pch=16,cex=.5)),auto.key=list(space="right",title="LULC"))+
317
  layer(panel.abline(lm(y~x),col="red"))+
318
  layer(panel.text(500,50,bquote(beta==.(round(coefficients(lm(y~x))[2],4)))))
319

    
320
## just forest, grouped by distance to coast
321
xyplot(value~dem|variable,groups=cut(DTCkm,breaks=c(0,300,1000)),melt(s@data[s$lulc=="Forest",c("DTCkm","dem","lulc",months)],id.vars=c("DTCkm","dem","lulc")),pch=16,cex=.5,
322
       main="Month-by-month scatterplots of Elevation and LST, grouped by Distance to Coast",
323
       sub="Showing only forest class",ylab="LST",
324
       par.settings = list(superpose.symbol = list(pch=16,cex=.5)),auto.key=list(space="right",title="Distance to \n Coast (km)"))+
325
  layer(panel.abline(lm(y~x),col="red"))+
326
  layer(panel.text(500,50,bquote(beta==.(round(coefficients(lm(y~x))[2],4)))))
327

    
328
useOuterStrips(xyplot(value~dem|variable+lulc,groups=cut(DTCkm,breaks=c(0,300,1000)),
329
                      melt(s@data[s$lulc!="Snow",c("DTCkm","dem","lulc",months)],id.vars=c("DTCkm","dem","lulc")),pch=16,cex=.5,
330
       main="Month-by-month scatterplots of Elevation and LST, grouped by LULC and colored by distance to coast",
331
       sub="One point per pixel, per month",ylab="LST",
332
       par.settings = list(superpose.symbol = list(pch=16,cex=.5)),auto.key=list(space="right",title="Distance to \n Coast (km)")))+
333
  layer(panel.abline(lm(y~x),col="red"))
334

    
335

    
336

    
337
##########################################
338
### Model output
339

    
340
### show fitted values
341
spplot(s,zcol="demb",col.regions=terrain.colors(5),cex=.5)+layer(sp.lines(roi,lwd=1.2,col="black"))+
342
  layer(sp.points(s2,col="blue",pch=13,cex=2,lwd=2))+
343
  layer(sp.points(st2,col="black",lwd=1.5))
344

    
345

    
346
## look at correlation of LULC variables
347
lulct=s@data[,colnames(s@data)[colnames(s@data)%in%unique(s$lulc)]]
348
lulcc=cor(lulct)[order(cor(lulct)[1,]),order(cor(lulct)[1,])]
349
round(cor(lulct),2)
350
#print(xtable(round(cor(lulct),2),include.row.names=F))
351
plotcorr(lulcc,col=colors <- c("#A50F15","#DE2D26","#FB6A4A","#FCAE91","#FEE5D9","white","#EFF3FF","#BDD7E7","#6BAED6","#3182BD","#08519C")[5*lulcc+6],
352
         main="Correlation Matrix")
353

    
354
t1=as.data.frame(table(s$lulc));colnames(t1)=c("class","samplefreq")
355
t1$sampleprop=t1$samplefreq/sum(t1$samplefreq)
356
t2=as.data.frame(table(st2$lulc))
357
t1$stationfreq=0
358
t1$stationfreq[t1$class%in%t2$Var1]=t2$Freq[match(t2$Var1,t1$class[t1$class%in%t2$Var1])]
359
t1$stationprop=t1$stationfreq/sum(t1$stationfreq)
360
print(xtable(t1[,c(1,3,5)]),include.rownames=F)
361

    
362
### two plots of model parameters by month to show the effects of LULC and topography on LST
363
## Spatial
364
xyplot(Q50~month|parm,data=ms1[ms1$type=="Spatial",],panel=function(x,y,subscripts){
365
  tms1=ms1[ms1$type=="Spatial",][subscripts,]
366
  panel.segments(tms1$month,tms1$Q2.5,tms1$month,tms1$Q97.5,groups=tms1$parm,subscripts=1:nrow(tms1))
367
  panel.xyplot(tms1$month,tms1$Q50,pch=16,type="l")
368
  panel.abline(h=0,lty="dashed",col="grey")
369
},auto.key=list(space="right"),par.settings = list(superpose.symbol = list(pch=16,cex=.5,col=1:15),superpose.line=list(col=1:15)),
370
       subscripts=T,scales=list(y=list(relation="free",rot=90)),ylab="Parameter Coefficient (slope) with 95% Credible Intervals",xlab="Month",
371
       main="Spatial Parameters",
372
       sub="")
373

    
374
## LULC
375
xyplot(Q50~month,groups=parm,data=ms1[ms1$type=="LULC",],panel=function(x,y,subscripts){
376
  tms1=ms1[ms1$type=="LULC",][subscripts,]
377
  sig=ifelse(tms1$Q2.5<0&tms1$Q97.5<0|tms1$Q2.5>0&tms1$Q97.5>0,"red","black")
378
  panel.segments(tms1$month,tms1$Q2.5,tms1$month,tms1$Q97.5,groups=tms1$parm,subscripts=1:nrow(tms1))
379
  panel.xyplot(tms1$month,tms1$Q50,groups=tms1$parm,pch=16,type="l",subscripts=1:nrow(tms1))
380
  panel.abline(h=0,lty="dashed",col="grey")
381
},auto.key=list(space="right"),par.settings = list(superpose.symbol = list(pch=16,cex=.5,col=1:15),superpose.line=list(col=1:15)),
382
       subscripts=T,scales=list(y=list(relation="free",rot=90)),ylab="Parameter Coefficient (slope) with 95% Credible Intervals",xlab="Month",
383
       main="Effects of LULC on LST",
384
       sub="Coefficients are unstandardized and represent the change in LST expected with a 1% increase in that class from 100% Forest")
385

    
386
## Topography
387
xyplot(Q50~month|parm,data=ms1[ms1$type=="Topography",],panel=function(x,y,subscripts){
388
  tms1=ms1[ms1$type=="Topography",][subscripts,]
389
  panel.segments(tms1$month,tms1$Q2.5,tms1$month,tms1$Q97.5,subscripts=1:nrow(tms1))
390
  panel.xyplot(tms1$month,tms1$Q50,groups=tms1$parm,pch=16,type="l",subscripts=1:nrow(tms1))
391
  panel.abline(h=0,lty="dashed",col="grey")
392
},auto.key=list(space="right"),par.settings = list(superpose.symbol = list(pch=16,cex=.5,col=1:15),superpose.line=list(col=1:15)),
393
       subscripts=T,scales=list(y=list(relation="free",rot=90)),ylab="Parameter Coefficient (slope) with 95% Credible Intervals",xlab="Month",
394
       main="Effects of Topography on LST",
395
       sub="Coefficients are unstandardized. Intercept is degrees C, eastwest and northsouth range \n from -1 (90 degree slope) to 0 (flat) to 1 (90 degree slope), and dem is m \n logDTCkm is in log(km), and y (lat) is m")
396

    
397
### Capture same pattern using only station data?
398

    
399

    
400
dev.off()
401

    
402
 shrinkpdf<-function(pdf,maxsize=1,suffix="_small",verbose=T){
403
   require(multicore)
404
   wd=getwd()
405
   td=paste(tempdir(),"/pdf",sep="")
406
   if(!file.exists(td)) dir.create(td)
407
   if(verbose) print("Performing initial compression")
408
   setwd(td)
409
   if(verbose) print("Splitting the PDF to parallelize the processing")
410
   system(paste("pdftk ",wd,"/",pdf," burst",sep=""))
411
   mclapply(list.files(td,pattern="pdf$"),function(f){
412
     ## loop through all pages, perform compression with with ps2pdf
413
     if(verbose) print("Performing initial compression")
414
       system(paste("ps2pdf -dUseFlateCompression=true ",td,"/",f," ",td,"/compressed_",f,sep=""))
415
        file.rename(paste(td,"/compressed_",f,sep=""),paste(td,"/",f,sep=""))
416
     ## get sysmte size
417
        size=file.info(paste(td,"/",f,sep=""))$size*0.000001 #get sizes of individual pages
418
        toobig=size>=maxsize
419
        if(verbose&toobig)  print(paste("Resizing ",basename(paste(td,"/",f,sep="")),sep=""))
420
        system(paste("gs -dBATCH -dTextAlphaBits=4 -dNOPAUSE -r300 -q -sDEVICE=png16m -sOutputFile=- -q ",paste(td,"/",f,sep="")," | convert -background transparent -quality 100 -density 300 - ",f,sep=""))
421
      })
422
        if(verbose) print("Compiling the final pdf")
423
        setwd(wd)
424
        system(paste("gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=",strsplit(pdf,".",fixed=T)[[1]][1],suffix,".pdf ",td,"/*.pdf",sep=""))
425
        file.remove(list.files(td,full=T))
426
       if(verbose) print("Finished!!")
427
}
428

    
429
shrinkpdf("output/lst_lulc.pdf")
(2-2/3)