-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilityFuns.R
2275 lines (1980 loc) · 87.6 KB
/
utilityFuns.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# this script contains some miscellaneous, but useful functions
logit <- function(x) {
log(x/(1-x))
}
expit <- function(x) {
res = exp(x)/(1+exp(x))
res[x > 100] = 1
res[x < -100] = 0
res
}
# Do precomputations for computing precision matrix for a single layer or a block diagonal sparse
# precision matrix for multiple layers
# kappa: scale of Matern covariance with smoothness 1
# xRange, yRange: x and y intervals in space over which basis elements are placed
# nx, ny: number of basis elements when counting along the lattive in
# x and y directions respectively (for the first layer)
# rho: sill (marginal variance) for first layer
# nLayer: number of lattice layers
# thisLayer: user should always set to 1 to get full block diagonal precision matrix
# for all layers
# alphas: weights on the variances of each layer. Scales rho for each layer.
# fastNormalize: simple normalization to make marginal variance = rho in center. Basis coefficients may have different variances
# assume there is a single kappa, rho is adjusted with alpha when there are multiple layers
# latticeInfo: an object returned by makeLatGrids
precomputationsQ = function(latticeInfo, thisLayer=1) {
# save layer info quantities
nLayer = length(latticeInfo)
nx = latticeInfo[[thisLayer]]$nx
ny = latticeInfo[[thisLayer]]$ny
xRange=latticeInfo[[thisLayer]]$xRangeKnots
yRange=latticeInfo[[thisLayer]]$yRangeKnots
knotPts = latticeInfo[[thisLayer]]$latCoords
# make (Laplacian) differential operators
Dnx = bandSparse(nx, k=0:1, diag=list(rep(-2, nx), rep(1, nx-1)), symmetric=TRUE)
Dny = bandSparse(ny, k=0:1, diag=list(rep(-2, ny), rep(1, ny-1)), symmetric=TRUE)
# generate x and y (Laplacian) differential operators
Inx = Diagonal(n=nx)
Iny = Diagonal(n=ny)
Bx = kronecker(Iny, Dnx)
By = kronecker(Dny, Inx)
Bxy = Bx + By
## now construct relevant row of A for value at midpoint at this layer, and Q matrix
# make mid lattice point
# xi = ceiling(nx/2)
# yi = ceiling(ny/2)
# midPt = matrix(c(seq(xRange[1], xRange[2], l=nx)[xi], seq(yRange[1], yRange[2], l=ny)[yi]), nrow=1)
midPt = matrix(c((xRange[1] + xRange[2])/2, (yRange[1] + yRange[2])/2), nrow=1)
Ai = makeA(midPt, latticeInfo, thisLayer=thisLayer, maxLayer=thisLayer)
# return results
# If multiple layers, return block diagonal sparse matrix
if(thisLayer == nLayer) {
return(list(list(Bxy=Bxy, Ai=Ai)))
}
else {
return(c(list(list(Bxy=Bxy, Ai=Ai)), precomputationsQ(latticeInfo, thisLayer+1)))
}
}
# Do precomputations for computing precision matrix for a single layer or a block diagonal sparse
# precision matrix for multiple layers. Return pre- constructed block diagonal matrices instead of
# individual matrices going into the block diagonal
# kappa: scale of Matern covariance with smoothness 1
# xRange, yRange: x and y intervals in space over which basis elements are placed
# nx, ny: number of basis elements when counting along the lattive in
# x and y directions respectively (for the first layer)
# rho: sill (marginal variance) for first layer
# nLayer: number of lattice layers
# thisLayer: user should always set to 1 to get full block diagonal precision matrix
# for all layers
# alphas: weights on the variances of each layer. Scales rho for each layer.
# fastNormalize: simple normalization to make marginal variance = rho in center. Basis coefficients may have different variances
# assume there is a single kappa, rho is adjusted with alpha when there are multiple layers
# latticeInfo: an object returned by makeLatGrids
precomputationsQ2 = function(latticeInfo) {
out = precomputationsQ(latticeInfo, 1)
Bxys = lapply(out, function(x) {x$Bxy})
Ais = lapply(out, function(x) {x$Ai})
Bxy = bdiag(Bxys)
mBxymBxyT = -Bxy - t(Bxy) # - Bxy - t(Bxy)
BxyTBxy = t(Bxy) %*% Bxy # t(Bxy) %*% Bxy
A = bdiag(Ais)
At = t(A)
ms = sapply(out, function(x) {length(x$Ai)})
list(mBxymBxyT=mBxymBxyT, BxyTBxy=BxyTBxy, A=A, At=At, ms=ms)
}
# precompute normalization constants using natural smoothing spline on log log scale
precomputeNormalization = function(xRangeDat=c(-1,1), yRangeDat=c(-1,1), effRangeRange=NULL, nLayer=3, NC=13,
nBuffer=5, nKnots=NULL, saveResults=FALSE, doFinalTest=!saveResults,
latticeInfo=NULL, plotNormalizationSplines=TRUE) {
# construct lattice info if necessary, precompute relevant matrices
if(is.null(latticeInfo))
latticeInfo = makeLatGrids(xRangeDat, yRangeDat, NC, nBuffer, nLayer)
else {
xRangeDat = latticeInfo[[1]]$xRangeDat
yRangeDat = latticeInfo[[1]]$yRangeDat
nLayer = length(latticeInfo)
NC = latticeInfo[[1]]$NC
nBuffer = latticeInfo[[1]]$nBuffer
}
precomputationsQ = precomputationsQ2(latticeInfo)
# if there are any missing layers, then we know that we are allowing for multiple kappas
latticeWidths = sapply(latticeInfo, function(x) {x$latWidth})
if(any(latticeWidths[2:length(latticeWidths)] != latticeWidths[1:(length(latticeWidths)-1)] / 2))
singleKappa = FALSE
else
singleKappa = TRUE
# set the range of effRange if necessary to be between half of the finest layer's lattice width and the data domain diameter
if(is.null(effRangeRange))
effRangeRange = c(latticeInfo[[nLayer]]$latWidth / 5, max(c(diff(xRangeDat), diff(yRangeDat))))
# set the number of knot points so that the second to largest point is roughly 95% of the maximum knot point if necessary
if(is.null(nKnots)) {
width = abs(log(.95))
nKnots = ceiling(diff(log(effRangeRange))/width) + 1
}
# set the values of effRange between which we want to interpolate
effRangeKnots = exp(seq(log(effRangeRange[1]), log(effRangeRange[2]), l=nKnots))
if(singleKappa) {
kappaKnots = sqrt(8)/effRangeKnots * latticeInfo[[1]]$latWidth
} else {
effRangeKnots = matrix(effRangeKnots, nrow=1)
kappaKnots = outer(sapply(latticeInfo, function(x) {x$latWidth}), c(sqrt(8)/effRangeKnots), "*")
}
# compute ctilde vector for each value of effective range. The ctilde value for one layer is independent of the
# kappa value in another layer. Hence, only univariate splines are necessary to precompute
# NOTE: multiply these by alphas = c(1/nLayer, ..., 1/nLayer) now, then divide by alpha later depending on alpha
if(singleKappa) {
ctildes = sapply(kappaKnots, makeQPrecomputed, precomputedMatrices=precomputationsQ, latticeInfo=latticeInfo,
alphas=rep(1/nLayer, nLayer), normalized=TRUE, fastNormalize=TRUE, returnctildes=TRUE) / nLayer
} else {
ctildes = apply(kappaKnots, 2, makeQPrecomputed, precomputedMatrices=precomputationsQ, latticeInfo=latticeInfo,
alphas=rep(1/nLayer, nLayer), normalized=TRUE, fastNormalize=TRUE, returnctildes=TRUE) / nLayer
}
# estimate splines:
# a^T %*% Q^(-1) %*% a /(rho * alpha) = ctildes
getSplineFun = function(cts) {
logFun = splinefun(log(effRangeKnots), log(cts), method = "hyman")
function(x, alpha) {exp(logFun(log(x)))/alpha}
}
funs = apply(ctildes, 1, getSplineFun)
fullFun = function(effRange, alphas) {
# sapply(alphas, funs, x=effRange)
res = numeric(nLayer)
for(i in 1:nLayer) {
if(length(effRange) == 1)
res[i] = funs[[i]](effRange, alphas[i])
else
res[i] = funs[[i]](effRange[i], alphas[i])
}
res
}
# plot functions
for(i in 1:nLayer) {
effRanges = seq(effRangeRange[1], effRangeRange[2], l=500)
thisctildes = funs[[i]](effRanges, alpha=1/nLayer)
if(plotNormalizationSplines) {
par(mfrow=c(1,1))
plot(effRanges, thisctildes, type="l", col="blue", main=paste0("Layer ", i), xlab="Effective Range", ylab="ctilde")
points(effRangeKnots, ctildes[i,]*nLayer, pch=19, cex=.3)
}
}
for(i in 1:nLayer) {
effRanges = seq(effRangeRange[1], effRangeRange[2], l=500)
thisctildes = funs[[i]](effRanges, alpha=1/nLayer)
if(plotNormalizationSplines) {
par(mfrow=c(1,1))
plot(log(effRanges), log(thisctildes), type="l", col="blue", main=paste0("Layer ", i), xlab="Log Effective Range", ylab="Log ctilde")
points(log(effRangeKnots), log(ctildes[i,]*nLayer), pch=19, cex=.3)
}
}
if(doFinalTest) {
# the true value of alphas doesn't matter as long as it is different than what was used in the precomputation
alphas = getAlphas(nLayer)
if(singleKappa) {
i = round(nKnots/2)
thisKappa = kappaKnots[i]
thisEffRange = effRangeKnots[i]
thisctildes = fullFun(thisEffRange, alphas)
} else {
i = round(nKnots/2)
thisKappa = kappaKnots[,i]
thisEffRange = effRangeKnots[i]
thisctildes = fullFun(thisEffRange, alphas)
}
Q = makeQPrecomputed(kappa=thisKappa, precomputedMatrices=precomputationsQ, latticeInfo=latticeInfo,
alphas=alphas, normalized=TRUE, fastNormalize=TRUE)
Q2 = makeQPrecomputed(kappa=thisKappa, precomputedMatrices=precomputationsQ, latticeInfo=latticeInfo,
alphas=alphas, normalized=TRUE, fastNormalize=TRUE, ctildes=thisctildes)
if(plotNormalizationSplines)
print(mean(abs(Q - Q2)))
}
# save functions
if(saveResults) {
allNCs = sapply(latticeInfo, function(x) {x$NC})
if(length(allNCs) == 1)
ncText = paste0("_NC", allNCs)
else {
tempText = do.call("paste0", as.list(c(allNCs[1], paste0("_", allNCs[-1]))))
ncText = paste0("_NC", tempText)
}
save(list(funs=funs, fullFun=fullFun, latInfo=latticeInfo),
file=paste0("ctildeSplines_nLayer", nLayer, ncText,
"_xmin", round(xRangeDat[1], 1), "_xmax", round(xRangeDat[2], 1),
"_ymin", round(yRangeDat[1], 1), "_ymax", round(yRangeDat[2], 1),
".RData"))
}
list(funs=funs, fullFun=fullFun)
}
# get the marginal variance for multi-resolution process
# tod: theta/delta, or theta/latticeWidth
# either nu or alphas must be non-null
getMultiMargVar = function(kappa=1, rho=1, tod=2.5, nLayer=3, nu=NULL, alphas=NULL, nx=NULL, ny=NULL,
xRange=c(0,1), yRange=xRange, xRangeDat=c(-2,1), yRangeDat=xRangeDat, nBuffer=5) {
# set alphas if nu has been set
if(!is.null(nu)) {
alphas = getAlphas(nLayer, nu)
}
# set nx and ny if necessary and add buffer to avoid edge effects
if(is.null(nx) || is.null(ny)) {
maxPt = ceiling(tod)*4 + 1
nx = maxPt
ny = maxPt
}
# generate knot lattice locations and filter out locations
# too far outside of the data domain
origNX = nx
origNY = ny
knotXs = seq(xRange[1], xRange[2], l=nx)
knotYs = seq(yRange[1], yRange[2], l=ny)
if(sum(knotXs > xRangeDat[2]) > nBuffer)
knotXs = knotXs[1:(length(knotXs) - (sum(knotXs > xRangeDat[2]) - nBuffer))]
if(sum(knotXs < xRangeDat[1]) > nBuffer)
knotXs = knotXs[(1 + sum(knotXs < xRangeDat[1]) - nBuffer):length(knotXs)]
if(sum(knotYs > yRangeDat[2]) > nBuffer)
knotYs = knotYs[1:(length(knotYs) - (sum(knotYs > yRangeDat[2]) - nBuffer))]
if(sum(knotYs < yRangeDat[1]) > nBuffer)
knotYs = knotYs[(1 + sum(knotYs < yRangeDat[1]) - nBuffer):length(knotYs)]
nx = length(knotXs)
ny = length(knotYs)
# sum the variances of each layer weighted by alphas
totalMargVar = c()
for(l in 1:nLayer) {
# get the layer marginal variances
layerMargVar = as.numeric(getMargVar(kappa, rho, tod, origNX*2^(l-1), origNY*2^(l-1), xRange=xRange, yRange=yRange,
xRangeDat=xRangeDat, yRangeDat=yRangeDat, nBuffer=nBuffer))
layerMargVar[1:2] = layerMargVar[1:2]*alphas[l]
if(l == 1)
totalMargVar = layerMargVar[1:2]
else
totalMargVar = totalMargVar + layerMargVar[1:2]
}
# add in a variance ratio column
totalMargVar = c(totalMargVar, totalMargVar[1]/totalMargVar[2])
names(totalMargVar) = c("actualVar", "theorVar", "inflation")
totalMargVar
}
# compute the marginal variance for a given resolution layer
# tod: theta/delta, or theta/latticeWidth
getMargVar = function(kappa=1, rho=1, tod=2.5, nx=NULL, ny=NULL, xRange=c(-1,2), yRange=xRange,
xRangeDat=c(0,1), yRangeDat=xRangeDat, nBuffer=5) {
# set nx and ny if necessary and add buffer to avoid edge effects
if(is.null(nx) || is.null(ny)) {
maxPt = ceiling(tod)*4 + 1
nx = maxPt
ny = maxPt
}
# generate knot lattice locations and filter out locations
# too far outside of the data domain
knotXs = seq(xRange[1], xRange[2], l=nx)
knotYs = seq(yRange[1], yRange[2], l=ny)
delta = knotXs[2]-knotXs[1]
if(sum(knotXs > xRangeDat[2]) > nBuffer)
knotXs = knotXs[1:(length(knotXs) - (sum(knotXs > xRangeDat[2]) - nBuffer))]
if(sum(knotXs < xRangeDat[1]) > nBuffer)
knotXs = knotXs[(1 + sum(knotXs < xRangeDat[1]) - nBuffer):length(knotXs)]
if(sum(knotYs > yRangeDat[2]) > nBuffer)
knotYs = knotYs[1:(length(knotYs) - (sum(knotYs > yRangeDat[2]) - nBuffer))]
if(sum(knotYs < yRangeDat[1]) > nBuffer)
knotYs = knotYs[(1 + sum(knotYs < yRangeDat[1]) - nBuffer):length(knotYs)]
knotPts = make.surface.grid(list(x=knotXs, y=knotYs))
# take the middle knot location
midPt = matrix(c(knotXs[ceiling(length(knotXs)/2)],
knotYs[ceiling(length(knotYs)/2)]), nrow=1)
# compute variance of process at the middle knot
A = as.matrix(makeA(midPt, xRange, nx, yRange, ny, tod*delta,
xRangeDat=xRangeDat, yRangeDat=yRangeDat, nBuffer=nBuffer))
Q = makeQ(kappa, rho, xRange, yRange, nx, ny,
xRangeDat=xRangeDat, yRangeDat=yRangeDat, nBuffer=nBuffer)
# VarC = as.matrix(solve(Q))
varMidPt = A %*% inla.qsolve(Q, t(A))
# compare with theoretical marginal variance
sigma2 = rho/(4*pi * kappa^2)
inflation = varMidPt/sigma2
# return results
list(actualVar=varMidPt, theorVar=sigma2, inflation=inflation)
}
# estimates effective range for a given LatticeKrig model
getEffRange = function(predPts=NULL, xRangeKnot=c(0,1), xNKnot=10, yRangeKnot=c(0,1), yNKnot=10, theta=NULL, nLayer=1, thisLayer=1,
xRangeDat=xRangeKnot, yRangeDat=yRangeKnot, nBuffer=5, mx=20, my=20) {
}
##### simulate from a latticeKrig model
# return a function with argument nsim for simulating a number of realizations from a latticeKrig model with no nugget.
# coords: coordinates at which to simulate
# all other arguments: same as general latticeKrig arguments
LKSimulator = function(coords, NC=5, kappa=1, rho=1, nu=1.5, nBuffer=5, nLayer=3, normalize=TRUE) {
# first make the grid on which to set the basis functions
xRangeDat = range(coords[,1])
yRangeDat = range(coords[,2])
knotGrid = makeLatGrid(xRange=xRangeDat, yRange=yRangeDat, NC=NC, nBuffer=nBuffer)
xRangeKnots=knotGrid$xRangeKnots
nx=knotGrid$nx
yRangeKnots=knotGrid$yRangeKnots
ny=knotGrid$ny
# generate layer variance weights
alphas = getAlphas(nLayer, nu)
# generate basis function and precision matrices
AObs = makeA(coords, xRangeKnots, nx, yRangeKnots, ny, nLayer=nLayer, xRangeDat=xRangeDat,
yRangeDat=yRangeDat, nBuffer=nBuffer)
Q = makeQ(kappa=kappa, rho=rho, xRange=xRangeBasis, yRange=yRangeBasis, nx=nx, ny=ny,
nLayer=nLayer, alphas=alphas, xRangeDat=xRangeDat, yRangeDat=yRangeDat,
nBuffer=nBuffer, normalized = normalize)
L = as.matrix(t(chol(solve(Q))))
zsim = matrix(rnorm(nrow(Q)), ncol=1)
fieldSim = L %*% zsim
fieldSims
}
# return a function with argument nsim for simulating a number of realizations from a latticeKrig model with no nugget.
# same as LKSimulator, but uses marginal variance, effective range parameterization instead of rho, kappa.
# coords: coordinates at which to simulate
# all other arguments: same as general latticeKrig arguments
LKSimulator2 = function(coords, nsim=1, NC=5, effRange=(max(coords[,1])-min(coords[,1]))/3, margVar=1,
nu=1.5, nBuffer=5, nLayer=3, normalize=TRUE) {
# first make the grid on which to set the basis functions
xRangeDat = range(coords[,1])
yRangeDat = range(coords[,2])
knotGrid = makeLatGrid(xRange=xRangeDat, yRange=yRangeDat, NC=NC, nBuffer=nBuffer)
xRangeKnots=knotGrid$xRangeKnots
nx=knotGrid$nx
yRangeKnots=knotGrid$yRangeKnots
ny=knotGrid$ny
# convert from effRange, margVar to rho, kappa
latticeWidth = (xRangeKnots[2] - xRangeKnots[1])/(nx-1)
kappa = sqrt(8)/effRange * latticeWidth
# since we are normalizing the process, rho is just sigmaSq
rho = margVar
# generate layer variance weights
alphas = getAlphas(nLayer, nu)
# generate basis function and precision matrices
AObs = makeA(coords, xRangeKnots, nx, yRangeKnots, ny, nLayer=nLayer, xRangeDat=xRangeDat,
yRangeDat=yRangeDat, nBuffer=nBuffer)
Q = makeQ(kappa=kappa, rho=rho, xRange=xRangeKnots, yRange=yRangeKnots, nx=nx, ny=ny,
nLayer=nLayer, alphas=alphas, xRangeDat=xRangeDat, yRangeDat=yRangeDat,
nBuffer=nBuffer, normalized = normalize)
L = as.matrix(t(chol(solve(Q))))
zsims = matrix(rnorm(nrow(Q)*nsim), ncol=nsim)
fieldSims = matrix(as.numeric(AObs %*% L %*% zsims), ncol=nsim)
fieldSims
}
simSPDE = function(coords, nsim=1, mesh=NULL, effRange=(max(coords[,1])-min(coords[,1]))/3, margVar=1) {
# generate mesh grid if necessary
if(is.null(mesh)) {
mesh = getSPDEMeshGrid(coords, doPlot = FALSE)
}
# calculate SPDE model parameters based on Lindgren Rue (2015) "Bayesian Spatial Modelling with R-INLA"
meshSize <- min(c(diff(range(mesh$loc[, 1])), diff(range(mesh$loc[, 2]))))
# it is easier to use theta and set sigma0 to 1 then to set sigma0 and the effective range directly
# kappa0 <- sqrt(8)/effRange * meshSize # since nu = 1
# kappa0 <- sqrt(8)/effRange # since nu = 1
# kappa0 = sqrt(8) / 5
# logKappa = log(kappa0)
sigma0 = 1
# tau0 <- 1/(sqrt(4 * pi) * kappa0 * sigma0)
# logTau = log(tau0)
# from page 5 of the paper listed above:
logKappa = 0.5 * log(8)
logTau = 0.5 * (lgamma(1) - (lgamma(2) + log(4*pi))) - logKappa
theta = c(log(sqrt(margVar)), log(effRange))
spde <- inla.spde2.matern(mesh, B.tau = cbind(logTau, -1, +1),
B.kappa = cbind(logKappa, 0, -1), theta.prior.mean = theta,
theta.prior.prec = c(0.1, 1))
# generate A and Q precision matrix
Q = inla.spde2.precision(spde, theta = theta)
A = inla.spde.make.A(mesh, coords)
# generate simulations
simField = inla.qsample(nsim, Q)
simDat = as.matrix(A %*% simField)
simDat
}
makeQSPDE = function(mesh, effRange, margVar=1) {
# calculate SPDE model parameters based on Lindgren Rue (2015) "Bayesian Spatial Modelling with R-INLA"
# it is easier to use theta and set sigma0 to 1 then to set sigma0 and the effective range directly
# kappa0 <- sqrt(8)/effRange * meshSize # since nu = 1
# kappa0 <- sqrt(8)/effRange # since nu = 1
# kappa0 = sqrt(8) / 5
# logKappa = log(kappa0)
sigma0 = 1
# tau0 <- 1/(sqrt(4 * pi) * kappa0 * sigma0)
# logTau = log(tau0)
# from page 5 of the paper listed above:
logKappa = 0.5 * log(8)
logTau = 0.5 * (lgamma(1) - (lgamma(2) + log(4*pi))) - logKappa
theta = c(log(sqrt(margVar)), log(effRange))
spde <- inla.spde2.matern(mesh, B.tau = cbind(logTau, -1, +1),
B.kappa = cbind(logKappa, 0, -1), theta.prior.mean = theta,
theta.prior.prec = c(0.1, 1))
# generate Q precision matrix
inla.spde2.precision(spde, theta = theta)
}
# computing precision matrix for a single layer or a block diagonal sparse
# precision matrix for multiple layers
# kappa: scale of Matern covariance with smoothness 1
# xRange, yRange: x and y intervals in space over which basis elements are placed
# nx, ny: number of basis elements when counting along the lattive in
# x and y directions respectively (for the first layer)
# rho: sill (marginal variance) for first layer
# nLayer: number of lattice layers
# thisLayer: user should always set to 1 to get full block diagonal precision matrix
# for all layers
# alphas: weights on the variances of each layer. Scales rho for each layer.
# fastNormalize: simple normalization to make marginal variance = rho in center. Basis coefficients may have different variances
# assume there is a single kappa, rho is adjusted with alpha when there are multiple layers
# latticeInfo: an object returned by makeLatGrids
makeQ = function(kappa=1, rho=1, latticeInfo, thisLayer=1, alphas=NULL, nu=NULL,
normalized=FALSE, fastNormalize=FALSE, precomputedMatrices=NULL) {
require(Matrix)
require(spam)
require(fields)
# save base layer input quantities
origRho = rho
nLayer = length(latticeInfo)
# make alphas according to nu relation if nu is set
if(is.null(alphas) && !is.null(nu)) {
alphas = getAlphas(nLayer, nu)
}
else if(is.null(nu) && nLayer != 1 && is.null(alphas)) {
warning("Both alphas and nu are NULL. Defaulting to exponential covariance.")
nu = 0.5
alphas = getAlphas(nLayer, nu)
}
nx = latticeInfo[[thisLayer]]$nx
ny = latticeInfo[[thisLayer]]$ny
if(is.null(precomputedMatrices)) {
# make (Laplacian) differential operators
Dnx = bandSparse(nx, k=0:1, diag=list(rep(-2, nx), rep(1, nx-1)), symmetric=TRUE)
Dny = bandSparse(ny, k=0:1, diag=list(rep(-2, ny), rep(1, ny-1)), symmetric=TRUE)
# generate x and y (Laplacian) differential operators
Inx = Diagonal(n=nx)
Iny = Diagonal(n=ny)
Bx = kronecker(Iny, Dnx)
By = kronecker(Dny, Inx)
Bxy = Bx + By
}
else
Bxy = precomputedMatrices[[thisLayer]]$Bxy
# make B, SAR regression matrix for Bc = e
B = Diagonal(n=nx*ny, x=kappa^2) - Bxy
# compute precision matrix
Q = t(B) %*% B
if(normalized) {
# now construct relevant row of A for value at midpoint at this layer, and Q matrix
if(is.null(precomputedMatrices)) {
xRange=latticeInfo[[thisLayer]]$xRangeKnots
yRange=latticeInfo[[thisLayer]]$yRangeKnots
# make mid lattice point
# xi = ceiling(nx/2)
# yi = ceiling(ny/2)
# midPt = matrix(c(seq(xRange[1], xRange[2], l=nx)[xi], seq(yRange[1], yRange[2], l=ny)[yi]), nrow=1)
midPt = matrix(c((xRange[1] + xRange[2])/2, (yRange[1] + yRange[2])/2), nrow=1)
Ai = makeA(midPt, latticeInfo, thisLayer=thisLayer, maxLayer=thisLayer)
}
else
Ai = precomputedMatrices[[thisLayer]]$Ai
# # test
# sds2 = 1/diag(Q)
# sdMat = Diagonal(x=sds2)
# # Qnorm2 = sweep(sweep(Q, 1, sds2, "*"), 2, sds2, "*")
# Qnorm2 = sdMat %*% Q %*% sdMat
#
# # QnormInv = sweep(sweep(Qinv, 1, 1/sds), 2, 1/sds)
# procVar2 = as.numeric(Ai %*% inla.qsolve(Qnorm2, t(Ai)))
# # procVar = as.numeric(Ai %*% QnormInv %*% t(Ai))
# Q2 = Qnorm2 * (procVar2 / rho)
# # Q = Q2 # system.time(out <- makeQ(nLayer=3, nx=15, ny=15, nu=1, normalized=TRUE, newnormalize=TRUE)): ~5.8s
# test 2
if(fastNormalize) {
ctilde = as.numeric(Ai %*% inla.qsolve(Q, t(Ai)))
Qtilde = ctilde * Q
Q = Qtilde # system.time(out <- makeQ(nLayer=3, nx=15, ny=15, nu=1, normalized=TRUE, newnormalize=TRUE)): 2.72
}
else {
# renormalize basis coefficients to have constant variance, and the process to have unit variance
Qinv = inla.qsolve(Q, diag(nrow(Q)))
sds = sqrt(diag(Qinv))
sdMat = Diagonal(x=sds)
# Qnorm = sweep(sweep(Q, 1, sds, "*"), 2, sds, "*")
Qnorm = sdMat %*% Q %*% sdMat
# QnormInv = sweep(sweep(Qinv, 1, 1/sds), 2, 1/sds)
procVar = as.numeric(Ai %*% inla.qsolve(Qnorm, t(Ai)))
# procVar = as.numeric(Ai %*% QnormInv %*% t(Ai))
Q = Qnorm * procVar # system.time(out <- makeQ(nLayer=3, nx=15, ny=15, nu=1, normalized=TRUE) ~5.87
}
# # compute how good an approximation it was
# hist(diag(solve(Q)))
# hist(diag(solve(Q2)))
# hist(diag(solve(Qtilde)))
# image(Q)
# image(Q2)
# image(Qtilde)
}
if(nLayer == 1 && is.null(alphas))
alphas = 1
Q = Q * (1/alphas[thisLayer])
# return results
# If multiple layers, return block diagonal sparse matrix
if(thisLayer == nLayer) {
if(thisLayer == 1)
Q = Q * (1/rho)
return(Q)
}
else if((thisLayer == 1) && (nLayer != 1)) {
Q = bdiag(c(list(Q), makeQ(kappa, origRho, latticeInfo, thisLayer+1, alphas, normalized=normalized,
fastNormalize=fastNormalize)))
Q = Q * (1/rho)
return(Q)
}
else {
return(c(list(Q), makeQ(kappa, origRho, latticeInfo, thisLayer+1, alphas, normalized=normalized,
fastNormalize=fastNormalize)))
}
}
meanSegmentLength = function(mesh, filterLargerThan=NULL) {
t.sub = 1:nrow(mesh$graph$tv)
idx = cbind(mesh$graph$tv[t.sub, c(1:3, 1), drop = FALSE], NA)
x = mesh$loc[t(idx), 1]
y = mesh$loc[t(idx), 2]
indices = 1:4 + rep(seq(from=0, to=length(x)-5, by=5), each=4)
segx = x[indices]
segy = y[indices]
coords = cbind(segx, segy)
dists = rdist.vec(coords[1:(length(segx) - 1),], coords[2:length(segx),])
dists = dists[-seq(from=4, to=length(dists), by=4)]
if(!is.null(filterLargerThan))
dists = dists[dists <= filterLargerThan]
mean(dists)
}
# meanSegmentLength(getSPDEMeshKenya(), 50)
# meanSegmentLength(getSPDEMesh(), 0.01+1e-6)
LKINLA.cov = function(x1, x2, latticeInfo, kappa, alphas, rho=1, normalize=TRUE,
fastNormalize=TRUE,
precomputedMatrices=NULL, precomputedA1=NULL, precomputedA2=NULL,
precomputationsFileNameRoot="") {
ctildes = NULL
if(precomputationsFileNameRoot != "") {
# load in precomputations
load(paste0("savedOutput/precomputations/", precomputationsFileNameRoot, ".RData"))
if(!is.null(precomputedNormalizationFun)) {
if(length(kappa) == 1)
effectiveCor = sqrt(8) / kappa * latticeInfo[[1]]$latWidth
else
effectiveCor = sqrt(8) / kappa * sapply(latticeInfo, function(x) {x$latWidth})
ctildes = precomputedNormalizationFun$fullFun(effectiveCor, alphas)
}
}
if(!is.null(precomputedMatrices)) {
Q = makeQPrecomputed(precomputedMatrices, kappa, rho, latticeInfo, alphas, normalized=normalize,
fastNormalize=fastNormalize, ctildes=ctildes)
} else {
Q = makeQ(kappa, rho, latticeInfo, 1, alphas, normalized=normalize, fastNormalize=fastNormalize)
}
if(is.null(precomputedA1))
A1 = makeA(x1, latticeInfo, 1)
else
A1 = precomputedA1
if(is.null(precomputedA2))
A2 = makeA(x2, latticeInfo, 1)
else
A2 = precomputedA2
if(any(alphas == 0)) {
# in this case, we must be careful to only consider the layers with nonzero weights
includeI = rep(TRUE, nrow(Q))
thisI = 1
for(i in 1:length(latticeInfo)) {
startI = thisI
endI = startI - 1 + latticeInfo[[i]]$nx * latticeInfo[[i]]$ny
if(alphas[i] == 0) {
includeI[startI:endI] = FALSE
}
thisI = endI + 1
}
A1 = matrix(as.matrix(A1)[,includeI], nrow=nrow(A1))
A2 = matrix(as.matrix(A2)[,includeI], nrow=nrow(A2))
Q = Q[includeI,includeI]
}
# use A1 %*% inla.qsolve(Q, t(A2)) instead?
A1 %*% inla.qsolve(Q, t(A2))
}
LK.cov = function(x1, x2, LKinfo, a.wght, alphas, lambda, sigma, rho) {
# domainCoords = LKinfo$latticeInfo$grid.info$range
# nBuffer = LKinfo$latticeInfo$NC.buffer
# NC = max(LKinfo$latticeInfo$mxDomain[1,])
# LKrigSetup(domainCoords, nlevel=length(alphas), a.wght=a.wght, normalize=normalize,
# lambda=lambda, sigma=sigma, rho=rho)
if(length(a.wght) > 1)
a.wght = as.list(a.wght)
LKinfo = LKinfoUpdate(LKinfo, a.wght=a.wght, alpha=alphas, lambda=lambda, sigma=sigma, rho=rho)
LKrig.cov(x1, x2, LKinfo)
}
# make method for calculating individual covariance function
getLKInlaCovarianceFun = function(kappa, rho, nuggetVar, alphas, NP=200, latticeInfo, normalize=TRUE, fastNormalize=TRUE,
precomputedMatrices=NULL, precomputedAcenter=NULL, precomputedAx=NULL, precomputedAy=NULL) {
# generate test locations based on code from LKrig.cov.plot
xlim <- latticeInfo[[1]]$xRangeDat
ux <- seq(xlim[1], xlim[2], , NP)
ylim <- latticeInfo[[1]]$yRangeDat
uy <- seq(ylim[1], ylim[2], , NP)
center <- rbind(c(ux[NP/2], uy[NP/2]))
# calculate covariances
x1 <- cbind(ux, rep(center[2], NP))
x2 <- rbind(center)
d <- c(rdist(x1, x2))
y <- as.numeric(LKINLA.cov(x1, x2, latticeInfo, kappa, alphas, rho, normalize, fastNormalize,
precomputedMatrices, precomputedAx, precomputedAcenter))
y[NP/2] = y[NP/2] + nuggetVar
x1 <- cbind(rep(center[1], NP), uy)
d2 <- c(rdist(x1, x2))
y2 <- as.numeric(LKINLA.cov(x1, x2, latticeInfo, kappa, alphas, rho, normalize, fastNormalize,
precomputedMatrices, precomputedAy, precomputedAcenter))
y2[NP/2] = y2[NP/2] + nuggetVar
# average x and y covariances
sortXI = sort(d, index.return=TRUE)$ix
d = d[sortXI]
y = y[sortXI]
sortYI = sort(d2, index.return=TRUE)$ix
d2 = d2[sortYI]
y2 = y2[sortYI]
d = rowMeans(cbind(d, d2))
y = rowMeans(cbind(y, y2))
return(cbind(d=d, cov=y, cor=y * (1 / max(y))))
}
covarianceDistributionLKINLA = function(latticeInfo, kappaVals, rhoVals=rep(1, length(kappaVals)), nuggetVarVals=rep(0, length(kappaVals)),
alphaMat, maxSamples=100, significanceCI=.8, normalize=TRUE, fastNormalize=TRUE, seed=NULL, NP = 200,
precomputationsFileNameRoot="", maxRadius=NULL) {
if(!is.null(seed))
set.seed(seed)
nLayer = length(latticeInfo)
# get hyperparameter samples
sampleI = sample(1:length(rhoVals), min(maxSamples, length(rhoVals)))
if(!is.null(dim(kappaVals))) {
kappaVals = kappaVals[,sampleI]
separateRanges = TRUE
effectiveRanges = sweep(sqrt(8)/kappaVals, 1, sapply(latticeInfo, function(x){x$latWidth}), "*")
minRange = min(apply(effectiveRanges, 1, min))
maxRange = max(apply(cbind(5 * sapply(latticeInfo, function(x){x$latWidth}), effectiveRanges), 1, max))
} else {
kappaVals = kappaVals[sampleI]
separateRanges = FALSE
effectiveRanges = sqrt(8) * latticeInfo[[1]]$latWidth / kappaVals
minRange = min(effectiveRanges) / 2^(length(latticeInfo) - 1)
maxRange = max(c(effectiveRanges, latticeInfo[[1]]$latWidth * 5))
}
rhoVals = rhoVals[sampleI]
nuggetVarVals = nuggetVarVals[sampleI]
alphaMat = matrix(alphaMat[,sampleI], ncol=length(sampleI))
# generate test locations based on code from LKrig.cov.plot (modify sampling points to be the correct resolution)
# xlim <- latticeInfo[[1]]$xRangeDat
# ux <- seq(xlim[1], xlim[2], , NP)
# ylim <- latticeInfo[[1]]$yRangeDat
# uy <- seq(ylim[1], ylim[2], , NP)
# center <- rbind(c(ux[NP/2], uy[NP/2]))
if(is.null(maxRadius))
maxRadius = maxRange * 2
minStep = minRange / 10
ThisNP = 2 * maxRadius / minStep
xlim <- latticeInfo[[1]]$xRangeDat
ylim <- latticeInfo[[1]]$yRangeDat
# centerX = mean(xlim)
# widthX = xlim[2] - centerX
# deltaX = min(widthX, maxRadius)
# xlim = c(centerX - deltaX, centerX + deltaX)
# ux <- seq(xlim[1], xlim[2], , NP)
# ylim <- latticeInfo[[1]]$yRangeDat
# centerY = mean(ylim)
# widthY = ylim[2] - centerY
# deltaY = min(widthY, maxRadius)
# ylim = c(centerY - deltaY, centerY + deltaY)
# uy <- seq(ylim[1], ylim[2], , NP)
# center <- rbind(c(ux[NP/2], uy[NP/2]))
centerX = mean(xlim)
widthX = xlim[2] - centerX
deltaX = min(widthX, maxRadius)
centerY = mean(ylim)
widthY = ylim[2] - centerY
deltaY = min(widthY, maxRadius)
delta = min(deltaX, deltaY)
xlim = c(centerX - delta, centerX + delta)
# ux <- seq(xlim[1], xlim[2], , NP)
ux <- c(seq(xlim[1], centerX-minRange/100, l=NP/2), centerX, seq(centerX+minRange/100, xlim[2], l=NP/2))
ylim = c(centerY - delta, centerY + delta)
# uy <- seq(ylim[1], ylim[2], , NP)
uy <- c(seq(ylim[1], centerY-minRange/100, l=NP/2), centerY, seq(centerY+minRange/100, ylim[2], l=NP/2))
center <- rbind(c(centerX, centerY))
# precompute relevant matrices
Qprecomputations = precomputationsQ2(latticeInfo)
Acenter = makeA(center, latticeInfo)
Ax = makeA(cbind(ux, center[2]), latticeInfo)
Ay = makeA(cbind(center[1], uy), latticeInfo)
# make method for calculating individual covariance function
getOneCovariance = function(parameters) {
# get relevant parameters
if(!separateRanges) {
kappa = parameters[1]
rho = parameters[2]
nuggetVar = parameters[3]
alphas = parameters[-(1:3)]
} else {
kappa = parameters[1:nLayer]
rho = parameters[1 + nLayer]
nuggetVar = parameters[2 + nLayer]
alphas = parameters[-(1:(2 + nLayer))]
}
# calculate covariances
x1 <- cbind(ux, rep(center[2], NP+1))
x2 <- rbind(center)
d <- c(rdist(x1, x2))
y <- as.numeric(LKINLA.cov(x1, x2, latticeInfo, kappa, alphas, rho, normalize, fastNormalize,
Qprecomputations, Ax, Acenter, precomputationsFileNameRoot=precomputationsFileNameRoot))
y[NP/2+1] = y[NP/2+1] + nuggetVar
x1 <- cbind(rep(center[1], NP+1), uy)
d2 <- c(rdist(x1, x2))
y2 <- as.numeric(LKINLA.cov(x1, x2, latticeInfo, kappa, alphas, rho, normalize, fastNormalize,
Qprecomputations, Ay, Acenter, precomputationsFileNameRoot=precomputationsFileNameRoot))
y2[NP/2+1] = y2[NP/2+1] + nuggetVar
# average x and y covariances
# sortXI = sort(d, index.return=TRUE)$ix
# d = d[sortXI]
# y = y[sortXI]
# sortYI = sort(d2, index.return=TRUE)$ix
# d2 = d2[sortYI]
# y2 = y2[sortYI]
# d = rowMeans(cbind(d, d2))
# y = rowMeans(cbind(y, y2))
d = c(0, rowMeans(cbind(rev(d[1:(NP/2)]), d[(NP/2+2):length(d)], rev(d2[1:(NP/2)]), d2[(NP/2+2):length(d2)])))
y = c(mean(y[NP/2+1], y2[NP/2+1]), rowMeans(cbind(rev(y[1:(NP/2)]), y[(NP/2+2):length(y)], rev(y2[1:(NP/2)]), y2[(NP/2+2):length(y2)])))
sortXI = sort(d, index.return=TRUE)$ix
d = d[sortXI]
y = y[sortXI]
return(cbind(d=d, cov=y, cor=y * (1 / max(y))))
}
# calculate covariances for each sample from the posterior
if(!separateRanges)
parameterMat = cbind(kappaVals, rhoVals, nuggetVarVals, t(alphaMat))
else
parameterMat = cbind(t(kappaVals), rhoVals, nuggetVarVals, t(alphaMat))
# browser()
out = apply(parameterMat, 1, getOneCovariance)
d = out[1:(NP/2+1),1]
covMat = out[(NP/2+2):(2*(NP/2+1)),]
corMat = out[(2*(NP/2+1)+1):(3*(NP/2+1)),]
# calculate summary statistics
meanCov = rowMeans(covMat)
lowerCov = apply(covMat, 1, quantile, probs=(1-significanceCI)/2)
upperCov = apply(covMat, 1, quantile, probs=1 - (1-significanceCI)/2)
meanCor = rowMeans(corMat)
lowerCor = apply(corMat, 1, quantile, probs=(1-significanceCI)/2)
upperCor = apply(corMat, 1, quantile, probs=1 - (1-significanceCI)/2)
# return results
list(d=d,
cov=meanCov, upperCov=upperCov, lowerCov=lowerCov, covMat=covMat,
cor=meanCor, upperCor=upperCor, lowerCor=lowerCor, corMat=corMat)
}
covarianceDistributionLK = function(latticeInfo, alphaVals, lambdaVals, a.wghtVals, rhoVals,
maxSamples=100, significanceCI=.8, normalize=TRUE, seed=NULL) {
NP = 200
if(!is.null(seed))
set.seed(seed)
# get number of layers
nLayer = latticeInfo$nlevel
a.wghtVals = matrix(a.wghtVals, ncol=length(lambdaVals))
# get hyperparameter samples
nuggetVarVals = rhoVals * lambdaVals
sampleI = sample(1:length(rhoVals), maxSamples)
alphaMat = alphaVals[,sampleI]
lambdaVals = lambdaVals[sampleI]
a.wghtVals = matrix(a.wghtVals[,sampleI], ncol=maxSamples)
nuggetVarVals = nuggetVarVals[sampleI]
rhoVals = rhoVals[sampleI]
# generate test locations based on code from LKrig.cov.plot
xlim <- latticeInfo$latticeInfo$rangeLocations[,1]
ux <- seq(xlim[1], xlim[2], , NP)
ylim <- latticeInfo$latticeInfo$rangeLocations[,2]
uy <- seq(ylim[1], ylim[2], , NP)
center <- rbind(c(ux[NP/2], uy[NP/2]))
# make method for calculating individual covariance function
getOneCovariance = function(parameters) {
# get relevant parameters
a.wght = parameters[1:nrow(a.wghtVals)]
rho = parameters[nrow(a.wghtVals) + 1]
nuggetVar = parameters[nrow(a.wghtVals) + 2]
lambda = parameters[nrow(a.wghtVals) + 3]
alphas = parameters[-(1:(nrow(a.wghtVals) + 3))]
# calculate covariances
x1 <- cbind(ux, rep(center[2], NP))
x2 <- rbind(center)
d <- c(rdist(x1, x2))
y <- as.numeric(LK.cov(x1, x2, latticeInfo, a.wght, alphas, lambda, sqrt(nuggetVar), rho))
y[NP/2] = y[NP/2] + nuggetVar
x1 <- cbind(rep(center[1], NP), uy)
d2 <- c(rdist(x1, x2))
y2 <- as.numeric(LK.cov(x1, x2, latticeInfo, a.wght, alphas, lambda, sqrt(nuggetVar), rho))
y2[NP/2] = y2[NP/2] + nuggetVar
# calculate covariances excluding nugget
y3 = y
y3[NP/2] = y[NP/2] - nuggetVar
y4 = y2
y4[NP/2] = y2[NP/2] - nuggetVar
# average x and y covariances
sortXI = sort(d, index.return=TRUE)$ix
d = d[sortXI]
y = y[sortXI]
y3 = y3[sortXI]
sortYI = sort(d2, index.return=TRUE)$ix
d2 = d2[sortYI]
y2 = y2[sortYI]
y4 = y4[sortYI]
d = rowMeans(cbind(d, d2))
y = rowMeans(cbind(y, y2))
yNoNugget = rowMeans(cbind(y3, y4))
return(cbind(d=d, cov=y, cor=y * (1 / max(y)), covNoNugget=yNoNugget, norNoNugget=yNoNugget * (1 / max(yNoNugget))))
}
# calculate covariances for each sample from the posterior
parameterMat = cbind(t(a.wghtVals), rhoVals, nuggetVarVals, lambdaVals, t(alphaMat))
# browser()
out = apply(parameterMat, 1, getOneCovariance)
d = out[1:200,1]
covMat = out[201:400,]
corMat = out[401:600,]
covMatNoNugget = out[601:800,]
corMatNoNugget = out[801:1000,]
# calculate summary statistics
meanCov = rowMeans(covMat)
lowerCov = apply(covMat, 1, quantile, probs=(1-significanceCI)/2)
upperCov = apply(covMat, 1, quantile, probs=1 - (1-significanceCI)/2)
meanCor = rowMeans(corMat)
lowerCor = apply(corMat, 1, quantile, probs=(1-significanceCI)/2)
upperCor = apply(corMat, 1, quantile, probs=1 - (1-significanceCI)/2)
meanCovNoNugget = rowMeans(covMatNoNugget)
lowerCovNoNugget = apply(covMatNoNugget, 1, quantile, probs=(1-significanceCI)/2)
upperCovNoNugget = apply(covMatNoNugget, 1, quantile, probs=1 - (1-significanceCI)/2)
meanCorNoNugget = rowMeans(corMatNoNugget)
lowerCorNoNugget = apply(corMatNoNugget, 1, quantile, probs=(1-significanceCI)/2)
upperCorNoNugget = apply(corMatNoNugget, 1, quantile, probs=1 - (1-significanceCI)/2)
# return results
list(d=d,
cov=meanCov, upperCov=upperCov, lowerCov=lowerCov, covMat=covMat,
cor=meanCor, upperCor=upperCor, lowerCor=lowerCor, corMat=corMat,
covNoNugget=meanCovNoNugget, upperCovNoNugget=upperCovNoNugget, lowerCovNoNugget=lowerCovNoNugget, covMatNoNugget=covMatNoNugget,
corNoNugget=meanCorNoNugget, upperCorNoNugget=upperCorNoNugget, lowerCorNoNugget=lowerCorNoNugget, corMatNoNugget=corMatNoNugget)
}
covarianceDistributionSPDE = function(effectiveRangeVals, rhoVals=rep(1, length(effectiveRangeVals)), nuggetVarVals=rep(0, length(rhoVals)),
mesh, maxSamples=100, significanceCI=c(.8, .95), seed=NULL, xRangeDat=NULL, yRangeDat=NULL, NP = 200,
maxRadius=NULL) {
if(!is.null(seed))
set.seed(seed)
# get hyperparameter samples
sampleI = sample(1:length(effectiveRangeVals), maxSamples)
effectiveRangeVals = effectiveRangeVals[sampleI]
rhoVals = rhoVals[sampleI]
nuggetVarVals = nuggetVarVals[sampleI]
# generate test locations based on code from LKrig.cov.plot
if(is.null(xRangeDat) || is.null(yRangeDat)) {
idx = unique(c(mesh$segm$int$idx[,1], mesh$segm$int$idx[,2]))
locs = mesh$loc[idx,]
xlim = range(locs[,1])
ylim = range(locs[,2])
} else {
xlim = xRangeDat
ylim = yRangeDat
}
# ux <- seq(xlim[1], xlim[2], , NP)
# uy <- seq(ylim[1], ylim[2], , NP)
# center <- rbind(c(ux[NP/2], uy[NP/2]))
maxRange = max(effectiveRangeVals)
minRange = min(effectiveRangeVals)
if(is.null(maxRadius))
maxRadius = maxRange * 2
minStep = minRange / 10