-
Notifications
You must be signed in to change notification settings - Fork 0
/
fitModel.R
2953 lines (2575 loc) · 120 KB
/
fitModel.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
##### load in data and the necessary functions
library(fields)
setwd("~/git/M9/")
# source("loadFloodDat.R")
source("taper.R")
source("okada.R")
##### compute likelihood of GPS data
# Get likelihood of X in:
# X[i] = zeta[i] * xi[i],
# ( or X[i]/t(d, lambda) = ... )
# where
# zeta ~ exp(GP(muZeta, sigmaZeta * rhoZeta(.)))
# xi ~ exp(MVN(muXi, diag(sigmaXi)))
# and hence,
# logX ~ MVN(muXi + muZeta + log(t(d; lambda)), SigmaZeta + diag(sigmaXi))
# ( or logX ~ MVN(muXi + muZeta, SigmaZeta + diag(sigmaXi)) )
# The later seems preferable, since non-physical aspects of the GPS data
# imply it has not yet been tapered, but this might warrant looking into.
## inputs:
# muXi: mean of MVN in Log of xi (vector of GPS slip values). NOTE:
# this input is no longer required. It is estimated w/in the fxn
# muZeta: mean of GP in LOG of Zeta (constant). If vector then must be
# same length as GPS data
# SigmaZeta: Covariance of LOG of zeta (of dimension |sigmaXi|)
# gpsDat: GPS data restricted to CSZ fault geometry
GPSLnLik = function(muZeta, SigmaZeta, gpsDat=slipDatCSZ, tvec = rep(1, length(sigmaXi)),
normalModel=FALSE, corGPS=FALSE, doGammaSpline=FALSE, nKnotsGamma=7) {
if(any(is.na(tvec)) || any(tvec < 1e-4))
return(-10000)
##### get conditional MLE of muXi
# Calculate the standard error vector of xi. Derivation from week 08_30_17.Rmd presentation.
# Transformation from additive error to multiplicative lognormal model with asympototic
# median and variance matching.
sigmaXi = sqrt(log(.5*(sqrt(4*gpsDat$slipErr^2/gpsDat$slip^2 + 1) + 1)))
# estimate muXi MLE with inverse variance weighting
x = log(gpsDat$slip)
ci = 1/sigmaXi^2
ci = ci/sum(ci)
if(normalModel) {
x = gpsDat$slip
sigmaXi = sqrt(log(.5*(sqrt(4*gpsDat$slipErr^2/gpsDat$slip^2 + 1) + 1)))
ci = 1/sigmaXi^2
ci = ci/sum(ci)
if(doGammaSpline) {
# generate conditional estimate of gamma as a function of latitude using weighted least squares on log scale
ys = log(x)- log(muZeta) - log(tvec)
X = getSplineBasis(data.frame(list(latitude=gpsDat$lat)), nKnots=nKnotsGamma, latRange=latRange)
logModel = lm(ys~X-1, weights=ci)
gammaEst = exp(X %*% logModel$coefficients)
xCntr = x - gammaEst * tvec * muZeta
SigmaZeta = sweep(sweep(SigmaZeta, 1, tvec * gammaEst, "*"), 2, tvec * gammaEst, "*")
} else {
muXi = sum((log(x)- log(muZeta) - log(tvec))*ci)
gammaEst = exp(muXi)
xCntr = x - gammaEst * tvec * muZeta
if(any(tvec != 1))
SigmaZeta = sweep(sweep(SigmaZeta, 1, tvec, "*"), 2, tvec, "*")
SigmaZeta = gammaEst^2 * SigmaZeta
}
sigmaXi = gpsDat$slipErr
}
else {
if(doGammaSpline)
stop("fitting gamma not supported for lognormal model")
muXi = sum((x- muZeta - log(tvec))*ci)
xCntr = x - muZeta - muXi - log(tvec)
}
# if GPS measurement error is correlated, make it correlated in the same way as the latent process
if(corGPS) {
sigmaTZetas = sqrt(diag(SigmaZeta))
CXi = sweep(sweep(SigmaZeta, 1, 1/sigmaTZetas, "*"), 2, 1/sigmaTZetas, "*")
SigmaXi = sweep(sweep(CXi, 1, sigmaXi, "*"), 2, sigmaXi, "*")
Sigma = SigmaZeta + SigmaXi
}
else
Sigma = SigmaZeta + diag(sigmaXi^2)
# get likelihood
return(logLikGP(xCntr, chol(Sigma)))
}
# hist(solve(t(chol(Sigma))) %*% xCntr, freq=F)
# xs = seq(-4, 4, l=100)
# lines(xs, dnorm(xs),col="blue")
##### MVN log likelihood
## inputs:
# dat: observations. If multiple realizations, dat is a matrix with each column being a
# different set of observations for one realization
# SimgaU: upper triangular Cholesky decomp of covariance matrix
logLikGP = function(dat, SigmaU) {
if(!is.matrix(dat))
dat = matrix(dat, nrow=length(dat))
n = nrow(dat)
#calcualte GP log likelihood (log likelihood of S0j)
# (-1/2) t(y) %*% Sigma0^-1 y - (1/2) log det Sigma0 - (n/2) log(2pi)
# define z = U^-1 %*% y, and x = L^-1 %*% U^-1 %*% y
# then:
z = backsolve(SigmaU, dat, transpose=TRUE)
x = backsolve(SigmaU, z) #make sure x is a column
# get full loglik. First sum() only used for multiple realizations
log.likGP = sum(-(1/2) * colSums(dat * x) - sum(log(diag(SigmaU))) - (n/2)*log(2*pi))
return(log.likGP)
}
getGPSSubfaultDepths = function() {
# helper function for determining if GPS data is within a specific subfault geometry
getSubfaultGPSDat = function(i) {
row = csz[i,]
geom = calcGeom(row)
corners = geom$corners[,1:2]
in.poly(cbind(slipDat$lon, slipDat$lat), corners)
}
# construct logical matrix, where each column is the result of getSubfaultGPSDat(j)
# Hence, row represents data index, column represents subfault index.
inSubfaults = sapply(1:nrow(csz), getSubfaultGPSDat)
# get the depth of each subfault by taking mean
subfaultDepth = function(inds) {
subfaultDat = slipDat[inds,]
mean(subfaultDat$Depth)
}
apply(inSubfaults, 2, subfaultDepth)
}
##### Compute subsidence data likelihood
# same and subsidenceLnLik but cheats a tad to be faster. Downside is lnLik SE
# estimate is anti-conservative. Uses MC Likelihood estimation, but doesn't
# assume normality of subsidence data.
# muZeta: mean of log zeta field areal average values. If vector must be
# same length as nrow(fault)
subsidenceLnLikMod = function(G, cszDepths, SigmaZetaL, lambda, muZeta, nsim=3000,
subDat=dr1, tvec=taper(cszDepths, lambda=lambda)) {
# m is number of csz subfaults
m = nrow(SigmaZetaL)
# get log taper values
logt = log(tvec)
# get updated mean vector of GP in exponent of Zeta
meanZeta = logt + muZeta
# simulate G %*% T %*% Zeta (each col of sims is a simulation. nsim simulations for each event)
Zs = matrix(rnorm(m*nsim), nrow=m, ncol=nsim)
GPs0 = SigmaZetaL %*% Zs # mean zero
GPs = sweep(GPs0, 1, STATS = meanZeta, FUN="+")
Ss = exp(GPs)
sims = G %*% Ss
# y is the data, uncert is its standard deviation
y = -subDat$subsidence# MUST TAKE NEGATIVE HERE, SINCE SUBSIDENCE NOT UPLIFT!!!!
# uncert = subDat$Uncertainty
# Y[i] - (G %*% T %*% Zeta)[i] = eps[i]
simEps = sweep(-sims, 1, y, "+")
# # calculate the likelihood for the given event
# eventLnLik = function(i) {
# eventName = uniqueEvents[i]
# inds = as.character(dr1$event) == eventName
# thisUncert = uncert[inds]
#
# # calculate simulation likelihoods
# # NOTE: due to lack of numerical instability must estimate each individual observation's
# # likelihood, then log them, then sum them to get total log lik estimate.
# simLiks = function(simVals) {
# dnorm(simVals, sd=thisUncert)
# }
# colStart = (i-1)*nsim + 1
# colEnd = i*nsim
#
# # get the individual likelihoods for each simulated observation
# liks = apply(matrix(simEps[inds,], ncol=nsim), 2, simLiks)
#
# # take mean and get SE for estimate of each observation's lik
# if(!is.null(dim(liks))) {
# obsLiks = apply(liks, 1, mean)
# obsLikSEs = apply(liks, 1, sd)/sqrt(nsim)
# }
# else{
# obsLiks = mean(liks)
# obsLikSEs = sd(liks)/sqrt(nsim)
# }
#
# # convert to log like estimates
# obsLnLiks = log(obsLiks)
# obsLnLikSEs = obsLikSEs/obsLiks
#
# # get full event log-lik estimate
# lnLik = sum(obsLnLiks)
# lnLikSE = sqrt(sum(obsLnLikSEs^2))
# return(c(lnLik=lnLik, lnLikSE=lnLikSE))
# }
# get the individual likelihoods for each observation
likMat = apply(simEps, 2, dnorm, sd=subDat$Uncertainty)
obsLiks = apply(likMat, 1, mean)
obsLikSEs = apply(likMat, 1, sd)/sqrt(nsim)
# conver to log likelihoods
obsLnLiks = log(obsLiks)
obsLnLikSEs = obsLikSEs/obsLiks
#get full data log likelihood estimate
lnLik = sum(obsLnLiks)
lnLikSE = sqrt(sum(obsLnLikSEs^2))
# # get all event log likelihoods and standard errors
# lnLiks = sapply(1:length(uniqueEvents), eventLnLik)
# lnLikSEs = lnLiks[2,]
# lnLiks = lnLiks[1,]
#
# # now estimate total log likelihood. Get SE as well
# lnLik = sum(lnLiks)
# lnLikSE = sqrt(sum(lnLikSEs^2))
return(c(lnLik=lnLik, lnLikSE=lnLikSE))
}
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
# fitting functions assuming lambda0 (okada model elasticity) is fixed at 0.25
##### function for performing full MLE fit of model
# if muVec not included, params are of form:
# params[1]: lambda
# params[2]: muZeta
# params[3]: sigmaZeta
# params[4]: lambda0
# otherwise, they are of form:
# params[1]: lambda
# params[2]: sigmaZeta
# params[3]: lambda0
# NOTE: muXi is not required since it's estimated conditionally
# NOTE: currently the Okada model is the most time-consuming step in the optimization.
# It may help to do block optimization, fixing lambda0 for a while before changing it.
# Alternatively, we could assume lambda0=0.25 as is often done.
doFixedFit = function(initParams=NULL, nsim=500, useMVNApprox=FALSE, gpsDat=slipDatCSZ,
corMatGPS=NULL, muVec=NULL, G=NULL, subDat=dr1, dStar=21000, normalizeTaper=TRUE) {
##### Set up initial parameter guesses for the MLE optimization if necessary
if(is.null(initParams)) {
lambdaInit=2
muZetaInit = log(20)
# variance of a lognormal (x) is (exp(sigma^2) - 1) * exp(2mu + sigma^2)
# then sigma^2 = log(var(e^x)) - 2mu - log(e^(sigma^2) - 1)
# so sigma^2 \approx log(var(e^x)) - 2mu
# sigmaZetaInit = sqrt(log(var(dr1$subsidence)) - 2*muZetaInit)
sigmaZetaInit = 1
# muXiInit = log(2.25) # based on plots from exploratory analysis
if(is.null(muVec))
initParams = c(lambdaInit, muZetaInit, sigmaZetaInit)
else
initParams = c(lambdaInit, NA, sigmaZetaInit)
}
# get spatial correlation parameters (computed based on fitGPSCovariance)
corPar = getCorPar()
phiZeta = corPar$phiZeta
nuZeta = corPar$nuZeta
##### calculate correlation matrices for Zeta in km (for CSZ grid and the GPS data)
# NOTE: only the upper triangle is computed for faster computation. This is
# sufficient for R's Cholesky decomposition
# since we only want the correlation matrix, set sigmaZeta to 1
# coords = cbind(csz$longitude, csz$latitude)
# corMatCSZ = stationary.cov(coords, Covariance="Matern", theta=phiZeta,
# onlyUpper=TRUE, Distance="rdist.earth",
# Dist.args=list(miles=FALSE), smoothness=nuZeta)
# tmpParams = rep(1, 5)
# corMatCSZ = arealZetaCov(tmpParams, csz, nDown1=9, nStrike1=12)
# load the precomputed correlation matrix
arealCSZCor = getArealCorMat(fault)
corMatCSZ = arealCSZCor
corMatCSZL = t(chol(corMatCSZ))
coords = cbind(gpsDat$lon, gpsDat$lat)
if(is.null(corMatGPS)) {
corMatGPS = stationary.cov(coords, Covariance="Matern", theta=phiZeta,
onlyUpper=TRUE, smoothness=nuZeta,
Distance="rdist.earth", Dist.args=list(miles=FALSE))
}
# get Okada linear transformation matrix
if(is.null(G)) {
nx = 300
ny= 900
lonGrid = seq(lonRange[1], lonRange[2], l=nx)
latGrid = seq(latRange[1], latRange[2], l=ny)
G = okadaAll(csz, lonGrid, latGrid, cbind(subDat$Lon, subDat$Lat), slip=1, poisson=0.25)
}
##### calculate depths of the centers of the CSZ subfaults
cszDepths = getFaultCenters(csz)[,3]
##### Do optimization
optimTable <<- NULL # table to save likelihood optimization steps
controls = list(fnscale = -1, reltol=10^-5)
# must rename variables for hessian calculation
cszDepthsIn = cszDepthsIn
corMatGPSIn = corMatGPS
corMatCSZIn = corMatCSZ
corMatCSZLIn = corMatCSZL
phiZetaIn = phiZeta
gpsDatIn = gpsDat
nsimIn = nsim
dStarIn = dStar
normalizeTaperIn = normalizeTaper
useMVNApproxIn = useMVNApprox
muVecIn = muVec
GIn = G
subDatIn = subDat
opt = optim(initParams, fixedDataLogLik, control=controls, hessian=FALSE,
cszDepths=cszDepthsIn, corMatGPS=corMatGPSIn, corMatCSZL=corMatCSZLIn,
phiZeta=phiZetaIn, gpsDat=gpsDatIn, nsim=nsimIn, dStar=dStarIn, normalizeTaper=normalizeTaperIn,
useMVNApprox=useMVNApproxIn, muZeta=muVecIn, G=GIn, subDat=subDatIn)
# test = fullDataLogLik(initParams, cszDepths=cszDepths, corMatGPS=corMatGPS, corMatCSZL=corMatCSZL,
# phiZeta=phiZeta, slipDatCSZ=slipDatCSZ)
# get results of optimization
if(is.null(muVec)) {
lambdaMLE = opt$par[1]
muZetaMLE = opt$par[2]
sigmaZetaMLE = opt$par[3]
muZetaGPS = muZetaMLE
muZetaCSZ = muZetaMLE
}
else {
lambdaMLE = opt$par[1]
sigmaZetaMLE = opt$par[2]
muZetaMLE=muVec
muZetaGPS = muVec[1:nrow(gpsDat)]
muZetaCSZ = muVec[(nrow(gpsDat)+1):length(muVec)]
}
logLikMLE = opt$value
hess.args = list(eps=1e-4, d=0.0001, zero.tol=sqrt(.Machine$double.eps/7e-7), r=6, v=2, show.details=FALSE)
hess = hessian(fixedDataLogLik, opt$par,
cszDepths=cszDepthsIn, corMatGPS=corMatGPSIn, corMatCSZL=corMatCSZLIn,
phiZeta=phiZetaIn, gpsDat=gpsDatIn, nsim=nsimIn, dStar=dStarIn, normalizeTaper=normalizeTaperIn,
useMVNApprox=useMVNApproxIn, muZeta=muVecIn, G=GIn, subDat=subDatIn)
##### get conditional MLE of muXi
# Calculate the standard error vector of xi. Derivation from week 08_30_17.Rmd presentation.
# Transformation from additive error to multiplicative lognormal model with asympototic
# median and variance matching.
sigmaXi = sqrt(log(.5*(sqrt(4*gpsDat$slipErr^2/gpsDat$slip^2 + 1) + 1)))
# estimate muXi MLE with inverse variance weighting
logX = log(gpsDat$slip)
ci = 1/sigmaXi^2
ci = ci/sum(ci)
muXiMLE = sum((logX-muZetaGPS)*ci)
# params is in order: lambda, muZeta, sigmaZeta, lambda0, muXi
if(is.null(muVec))
MLEs = c(opt$par, 0.25, muXiMLE)
else
MLEs = c(opt$par[1], NA, opt$par[2], 0.25, muXiMLE)
# Return results
list(MLEs=MLEs, lambdaMLE=lambdaMLE, muZetaMLE=muZetaMLE, sigmaZetaMLE=sigmaZetaMLE, lambda0MLE=0.25,
muXiMLE=muXiMLE, logLikMLE=logLikMLE, hess=hess, optimTable=optimTable)
}
##### Computes the full data log likelihood given the parameters.
## inputs:
# if muZeta not provided directly, then:
# params[1]: lambda
# params[2]: muZeta
# params[3]: sigmaZeta
# else:
# params[1]: lambda
# params[2]: sigmaZeta
# NOTE: muXi was provided but there is an easy conditional estimate of this
fixedDataLogLik = function(params, cszDepths, gpsDat=slipDatCSZ,
subDat=dr1, fault=csz, verbose=TRUE,
G=NULL, nKnots=5, normalizeTaper=TRUE, dStar=21000,
constrLambda=TRUE, latRange=c(40,50),
distMatGPS=NULL, distMatCSZ=NULL,
corGPS=FALSE, diffGPSTaper=FALSE, nKnotsGPS=nKnots, anisotropic=FALSE,
squareStrikeDistCsz=NULL, squareDipDistCsz=NULL, squareStrikeDistGps=NULL,
squareDipDistGps=NULL, nKnotsGamma=7, doGammaSpline=FALSE, dStarGPS=dStar,
nKnotsVar=5, doVarSpline=FALSE) {
##### get parameters
out = getInputPar(params, fault, gpsDat, nKnots, diffGPSTaper, nKnotsGPS, taperedGPSDat=TRUE, anisotropic, normalModel=TRUE,
nKnotsVar, doVarSpline)
muZeta = out$muZeta
muVecCSZ = out$muVecCSZ
muVecGPS = out$muVecGPS
sigmaZeta = out$sigmaZeta
splinePar = out$taperPar
splineParGPS = out$taperParGPS
phiZeta = out$phiZeta
nuZeta = out$nuZeta
lambda0 = out$lambda0
alpha = out$alpha
varPar = out$varPar
parNames = out$parNames
muZetaGPS = muZeta
muZetaCSZ = muZeta
vecMu=FALSE
nuZeta = 3/2
# generate taper lambda parameter as a function of latitude for the subsidence data
tvec = getTaperSpline(splinePar, nKnots=nKnots, normalize=normalizeTaper, dStar=dStar, latRange=latRange, fault=fault)
Xi = getSplineBasis(fault, nKnots=nKnots, latRange=latRange)
lambda = Xi %*% splinePar # lambda is only used for checking if lambda < 0
# do the same for the gps data
XiGPS1 = getSplineBasis(data.frame(list(latitude=gpsDat$lat)), nKnots=nKnotsGPS, latRange=latRange)
lambda = XiGPS1 %*% splinePar
if(diffGPSTaper) {
XiGPS2 = getSplineBasis(data.frame(list(latitude=gpsDat$lat)), nKnots=nKnotsGPS, latRange=latRange)
lambda = lambda - XiGPS2 %*% splineParGPS
}
# calculate latent field standard deviation as a function of latitude for the subsidence data
if(doVarSpline) {
XiVar = getSplineBasis(fault, nKnots=nKnotsVar, latRange=latRange)
sigmaZeta = XiVar %*% varPar
XiVarGPS = getSplineBasis(data.frame(list(latitude=gpsDat$lat)), nKnots=nKnotsVar, latRange=latRange)
sigmaZetaGPS = XiVarGPS %*% varPar
}
## compute CSZ and GPS correlation matrices (use onlyUpper option to save time since will just take
## Cholesky decomposition of upper triangle anyway in both cases)
if(alpha >= 0.05 && phiZeta >= 0 && alpha <= 20) {
if(!anisotropic) {
coords = cbind(fault$longitude, fault$latitude)
if(phiZeta > 0) {
corMatCSZ = stationary.cov(coords, Covariance="Matern", theta=phiZeta,
onlyUpper=FALSE, distMat=distMatCSZ, smoothness=nuZeta)
corMatCSZL = t(chol(corMatCSZ))
# GPS covariance matrix
coords = cbind(gpsDat$lon, gpsDat$lat)
corMatGPS = stationary.cov(coords, Covariance="Matern", theta=phiZeta,
onlyUpper=FALSE, distMat=distMatGPS, smoothness=nuZeta)
}
}
else {
# compute distance matrices accounting for anisotropy
distMatCsz = sqrt(alpha^2 * squareStrikeDistCsz + (1 / alpha^2) * squareDipDistCsz)
distMatGps = sqrt(alpha^2 * squareStrikeDistGps + (1 / alpha^2) * squareDipDistGps)
# now generate correlation matrices and the Cholesky decomposition if necessary
corMatCSZ = stationary.cov(NA, Covariance="Matern", theta=phiZeta,
onlyUpper=FALSE, distMat=distMatCsz, smoothness=nuZeta)
corMatCSZL = t(chol(corMatCSZ))
corMatGPS = stationary.cov(NA, Covariance="Matern", theta=phiZeta,
onlyUpper=FALSE, distMat=distMatGps, smoothness=nuZeta)
}
}
lambda0 = 0.25
##### set up column names for parameter optimization table
cNames = c(parNames, "LL", "subLL", "GPSLL", "priorLL", "LLSE")
##### compute unit slip Okada seadef if necessary
if(is.null(G)) {
nx = 300
ny= 900
lonGrid = seq(lonRange[1], lonRange[2], l=nx)
latGrid = seq(latRange[1], latRange[2], l=ny)
G = okadaAll(csz, lonGrid, latGrid, cbind(subDat$Lon, subDat$Lat), slip=1, poisson=lambda0)
}
# plot taper (on original scale and GPS scale)
latSeq = seq(latRange[1], latRange[2], l=500)
splineMat = getSplineBasis(fault=fault, nKnots=nKnots, lats=latSeq, latRange=latRange)
lambdaSeq = splineMat %*% splinePar
lambdaSeqGPS = 0
if(diffGPSTaper) {
# add red line for GPS taper
XiGPS2 = getSplineBasis(fault=fault, nKnots=nKnotsGPS, lats=latSeq, latRange=latRange)
lambdaSeqGPS = lambdaSeq - XiGPS2 %*% splineParGPS
}
par(mfrow=c(1,2))
plot(latSeq, lambdaSeq, type="l", ylim=range(c(lambdaSeq, lambdaSeqGPS, 0)))
if(diffGPSTaper)
lines(latSeq, lambdaSeqGPS, col="red")
tmp = getTaperSpline(splinePar, nKnots=nKnots, dStar=dStar, latRange=latRange, fault=fault, normalize=normalizeTaper)
plotFault(fault, tmp, varRange=c(0, 1))
##### make sure params are in correct range and update optimTable
lambdaInRange=TRUE
if(constrLambda && any(lambdaSeq < 0) && any(lambdaSeqGPS < 0))
lambdaInRange = FALSE
else if(any(abs(lambdaSeq) > 15) && any(abs(lambdaSeqGPS) > 15))
lambdaInRange=FALSE
if(!lambdaInRange || any(sigmaZeta <= 0) || (muZeta <= 0) || (phiZeta <= 0) || (alpha <= 0.05) || (alpha >= 20)) {
newRow = rbind(c(params, -10000, -5000, -5000, 0, NA))
colnames(newRow) = cNames
if(verbose)
print(newRow)
optimTable <<- rbind(optimTable, newRow)
return(-10000) # return a very small likelihood
}
##### compute covariance of LOG of Zeta and its Cholesky decomp
if(doVarSpline) {
SigmaZetaGPS = sweep(sweep(corMatGPS, 1, sigmaZeta, "*"), 2, sigmaZeta, "*")
SigmaZetaCSZL = sweep(corMatCSZL, 1, sigmaZetaGPS, "*")
} else {
SigmaZetaGPS = sigmaZeta^2 * corMatGPS
SigmaZetaCSZL = sigmaZeta * corMatCSZL
}
##### Compute Likelihood of subsidence and GPS data
SigmaZeta = SigmaZetaCSZL %*% t(SigmaZetaCSZL)
sub = subsidenceLnLikMod2(muZetaCSZ, lambda, sigmaZeta, SigmaZeta, G, subDat=subDat,
tvec=tvec, dStar=dStar, normalizeTaper=normalizeTaper, normalModel=TRUE)
XiGPS1 = getSplineBasis(data.frame(list(latitude=gpsDat$lat)), nKnots=nKnots, latRange=latRange)
lambda = XiGPS1 %*% splinePar
if(diffGPSTaper) {
XiGPS2 = getSplineBasis(data.frame(list(latitude=gpsDat$lat)), nKnots=nKnots, latRange=latRange)
lambda = lambda - XiGPS2 %*% splineParGPS
}
tvecGPS = taper(gpsDat$Depth, lambda, alpha=2, dStar=dStarGPS, normalize=normalizeTaper)
GPS = GPSLnLik(muZetaGPS, SigmaZetaGPS, gpsDat, normalModel=TRUE, tvec=tvecGPS, corGPS=corGPS,
doGammaSpline=doGammaSpline, nKnotsGamma=nKnotsGamma)
lnLik = sub[1] + GPS
lnLikSE = sub[2]
priorLnLik = 0
##### update parameter optimization table
newRow = c(params, lnLik, sub[1], GPS, priorLnLik, lnLikSE)
newRow = rbind(newRow)
colnames(newRow) = cNames
if(verbose)
print(newRow, digits=5)
optimTable <<- rbind(optimTable, newRow)
##### return full data likelihood
lnLik
}
# jacobian(fixedDataLogLik, params, cszDepths=cszDepths, corMatGPS=corMatGPS, corMatCSZL=corMatCSZL, phiZeta=phiZeta,
# useMVNApprox=TRUE, G=G, nKnots=nKnots, dStar=dStar, useSubPrior=useSubPrior, useSlipPrior=useSlipPrior, fauxG=fauxG)
# starting quantile values:
# Browse[2]> getQS(params)
# [1] 238.1374
# Browse[2]> getQY(params, Xi=getSplineBasis(), G, fauxG)
# [1] 36.08274
# pars = splineFit21k5$MLEs
# pars = c(pars[2], pars[3], pars[6:length(pars)])
# getQS(pars)
# getQY(pars, getSplineBasis(), G, fauxG)
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
# calculate subsidence log likelihood assuming multivariate normal approximation
# to the lognormal distribution
source("approxDistn.R")
# Approximate the distribution of G %*% T %*% Zeta with a MVN to get likelihood
# here muZeta and sigmaZeta can be either a constant or a vector of length ncol(G)
subsidenceLnLikMod2 = function(muZeta, lambda, sigmaZeta, SigmaZeta, G, subDat=dr1,
tvec=taper(csz$depth, lambda=lambda, normalize=normalizeTaper),
dStar=21000, normalizeTaper=TRUE, normalModel=FALSE) {
# if sigmaZeta gets too large, variance explodes, getting lnLik is numerically infeasible
if(!normalModel && (any(sigmaZeta > 4) || any(sigmaZeta < 0)))
return(c(lnLik=-5000, lnLikSE=NA))
# This is the key step: approximate G %*% T %*% Zeta with a MVN
mvnApprox = estSubsidenceMeanCov(muZeta, lambda, SigmaZeta, G, subDat=subDat,
tvec=tvec, normalModel=normalModel)
mu = mvnApprox$mu
Sigma = mvnApprox$Sigma
# add data noise to covariance matrix
diag(Sigma) = diag(Sigma) + subDat$Uncertainty^2
# get log likelihood
y = -subDat$subsidence# MUST TAKE NEGATIVE HERE, SINCE SUBSIDENCE NOT UPLIFT!!!!
lnLik = logLikGP(y - mu, chol(Sigma))
return(c(lnLik=lnLik, lnLikSE=0))
}
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
# functions relating to variance inflation of GPS data:
# Do n-fold cross-validation over the subsidence data to determine optimal
# sd inflation additive factor. In other words, use all GPS data and only
# part of the subsidence data to fit the model, then compute the predictive
# likelihood of the left out data.
sdInflationCV = function(initParams=NULL, nfold=10, sdInflationGrid=NULL,
nsim=500, useMVNApprox=TRUE, subDat=dr1) {
##### Set up initial parameter guesses for the MLE optimization if necessary
if(is.null(initParams)) {
lambdaInit=2
muZetaInit = log(20)
# variance of a lognormal (x) is (exp(sigma^2) - 1) * exp(2mu + sigma^2)
# then sigma^2 = log(var(e^x)) - 2mu - log(e^(sigma^2) - 1)
# so sigma^2 \approx log(var(e^x)) - 2mu
# sigmaZetaInit = sqrt(log(var(dr1$subsidence)) - 2*muZetaInit)
sigmaZetaInit = 1
# muXiInit = log(2.25) # based on plots from exploratory analysis
initParams = c(lambdaInit, muZetaInit, sigmaZetaInit)
}
# get spatial correlation parameters (computed based on fitGPSCovariance)
corPar = getCorPar()
phiZeta = corPar$phiZeta
nuZeta = corPar$nuZeta
##### set up default grid sequence of values for sdInflationGrid
if(is.null(sdInflationGrid)) {
maxVal = 100
minVal = .05
sdInflationGrid = c(0, 10^seq(log10(minVal), log10(maxVal), l=19))
}
##### subset GPS data so it's only over the fault geometry
slipDatCSZ = getFaultGPSDat()
logX = log(slipDatCSZ$slip)
##### calculate correlation matrices for Zeta in km (for CSZ grid and the GPS data)
# NOTE: only the upper triangle is computed for faster computation. This is
# sufficient for R's Cholesky decomposition
# since we only want the correlation matrix, set sigmaZeta to 1
# coords = cbind(csz$longitude, csz$latitude)
# corMatCSZ = stationary.cov(coords, Covariance="Matern", theta=phiZeta,
# onlyUpper=TRUE, Distance="rdist.earth",
# Dist.args=list(miles=FALSE), smoothness=nuZeta)
tmpParams = rep(1, 5)
# get coordinates for GPS data
xs = cbind(slipDatCSZ$lon, slipDatCSZ$lat)
# calculate depths of the centers of the CSZ subfaults
cszDepths = getFaultCenters(csz)[,3]
# precompute areal and point to areal correlation matrices
params = c(NA,NA,1,NA,NA)
CorSB = pointArealZetaCov(params, xs, csz, nDown=9, nStrike=12)
CorS = stationary.cov(xs, Covariance="Matern", theta=phiZeta,
smoothness=nuZeta, Distance="rdist.earth",
Dist.args=list(miles=FALSE))
arealCSZCor = getArealCorMat(fault)
CorB = arealCSZCor
CorBL = t(chol(CorB))
# precompute Okada matrix
nx = 300
ny= 900
lonGrid = seq(lonRange[1], lonRange[2], l=nx)
latGrid = seq(latRange[1], latRange[2], l=ny)
GFull = okadaAll(csz, lonGrid, latGrid, cbind(subDat$Lon, subDat$Lat), slip=1, poisson=0.25)
##### Do cross-validation
# scramle the data (and save how to unscramble it)
scrambleInds = sample(1:nrow(subDat), nrow(subDat))
subDatScramble = subDat[scrambleInds,]
eventsScramble = events[scrambleInds]
unscrambleInds = sort(scrambleInds, index.return=TRUE)$ix
# preallocate variables to save during the CV and begin CV
lnLikGrid = matrix(NA, nrow=length(sdInflationGrid), ncol=nfold)
maxLnLik = -Inf
for(i in 1:length(sdInflationGrid)) {
sdInflation = sdInflationGrid[i]
print(paste0("sdInflation: ", sdInflation))
for(j in 1:nfold) {
# set subsidence data to be used for fitting
# (make sure data is still sorted by event)
predInds = ((1:nrow(subDat)) <= nrow(subDat)*j/nfold) &
(((1:nrow(subDat)) > nrow(subDat)*(j-1)/nfold))
fitInds = !predInds
scrambledFitInds = scrambleInds[fitInds]
thisEvents = events[scrambledFitInds]
ord = order(factor(thisEvents, levels=uniqueEvents))
YFitOrder = scrambledFitInds[ord]
subDatFit = subDat[YFitOrder,]
# add to GPS data's variance
gpsDatInflate = slipDatCSZ
gpsDatInflate$slipErr = gpsDatInflate$slipErr + sdInflation
# Do optimization
lastParams <<- NULL # used for updating Okada matrix only when necessary
optimTable <<- NULL # table to save likelihood optimization steps
controls = list(fnscale = -1, reltol=10^-5)
opt = optim(initParams, fixedDataLogLik, control=controls, hessian=TRUE,
cszDepths=cszDepths, corMatGPS=CorS, corMatCSZL=CorBL,
phiZeta=phiZeta, gpsDat=gpsDatInflate, subDat=subDatFit, nsim=nsim,
useMVNApprox=useMVNApprox, verbose=FALSE)
params = opt$par
# get fit MLEs
lambda = params[1]
muZeta = params[2]
sigmaZeta = params[3]
lambda0 = 0.25
# estimate muXi MLE with inverse variance weighting
# Calculate the standard error vector of xi. Derivation from week 08_30_17.Rmd presentation.
# Transformation from additive error to multiplicative lognormal model with asympototic
# median and variance matching.
sigmaXi = sqrt(log(.5*(sqrt(4*gpsDatInflate$slipErr^2/gpsDatInflate$slip^2 + 1) + 1)))
logX = log(slipDatCSZ$slip)
ci = 1/sigmaXi^2
ci = ci/sum(ci)
muXi = sum(logX*ci) - muZeta
# set all parameters optimized in fit
params = c(params, lambda0, muXi)
# get taper values
tvec = taper(cszDepths, lambda=lambda)
# compute G %*% T
GFit = GFull[YFitOrder,]
GTFit = sweep(GFit, 2, tvec, "*")
# get data for prediction
scrambledPredInds = scrambleInds[predInds]
thisEvents = events[scrambledPredInds]
ord = order(factor(thisEvents, levels=uniqueEvents))
YPredOrder = scrambledPredInds[ord]
subDatPred = subDat[YPredOrder,]
# compute G %*% T
GPred = GFull[YPredOrder,]
GTPred = sweep(GPred, 2, tvec, "*")
# get predictive distribution
SigmaSB = CorSB * sigmaZeta^2
SigmaS = CorS * sigmaZeta^2
SigmaB = CorB * sigmaZeta^2
SigmaYModFit = diag(exp(muZeta + diag(SigmaB)/2)) %*% t(GTFit)
SigmaYModPred = diag(exp(muZeta + diag(SigmaB)/2)) %*% t(GTPred)
# SigmaBYFit = SigmaB %*% SigmaYModFit
SigmaSYFit = SigmaSB %*% SigmaYModFit
SigmaSYPred = SigmaSB %*% SigmaYModPred
subDistn = getSubsidenceVarianceMat(params, fault=csz, G=GFull, subDat=subDat)
SigmaY = subDistn$Sigma
SigmaYFit = SigmaY[YFitOrder,YFitOrder]
SigmaYPred = SigmaY[YPredOrder,YPredOrder]
SigmaYPredToFit = SigmaY[YPredOrder, YFitOrder]
# now block them into predictions and data covariance matrices
SigmaP = SigmaYPred
SigmaD = cbind(rbind(SigmaS + diag(sigmaXi^2), t(SigmaSYFit)), rbind(SigmaSYFit, SigmaYFit))
SigmaPtoD = cbind(t(SigmaSYPred), SigmaYPredToFit)
# now get predictive likelihood of the left out subsidence data
fYPred = subLikGivenAll(params, SigmaPtoD, SigmaD, GPred=GPred, GFit=GFit,
subDatPred=subDatPred, subDatFit=subDatFit)
# get log likelihood
lnLik = fYPred
lnLikGrid[i,j] = lnLik
# check if this is the best run so far. If so store results
if(lnLik > maxLnLik) {
maxLnLik = lnLik
bestOpt = opt
bestOptimTable = optimTable
bestI = i
}
print(paste0("Rep ", j, "/", nfold, " complete with lnLik ", lnLik))
}
print(paste0("Mean lnLik for inflation factor of ", sdInflation, " is: ", mean(lnLikGrid[i,])))
}
# get results of optimization for the best CV value of sdInflation
bestSDInflation = sdInflationGrid[bestI]
lambdaMLE = bestOpt$par[1]
muZetaMLE = bestOpt$par[2]
sigmaZetaMLE = bestOpt$par[3]
muXiMLE = bestOpt$par[5]
logLikMLE = bestOpt$value
hess = bestOpt$hessian
##### get conditional MLE of muXi
# Calculate the standard error vector of xi. Derivation from week 08_30_17.Rmd presentation.
# Transformation from additive error to multiplicative lognormal model with asympototic
# median and variance matching.
sigmaXi = sqrt(log(.5*(sqrt(4*(slipDatCSZ$slipErr+bestSDInflation)^2/slipDatCSZ$slip^2 + 1) + 1)))
# estimate muXi MLE with inverse variance weighting
logX = log(slipDatCSZ$slip)
ci = 1/sigmaXi^2
ci = ci/sum(ci)
muXiMLE = sum(logX*ci) - muZetaMLE
# Return results
list(sdInflationGrid=sdInflationGrid, lnLikGrid=lnLikGrid, bestSDInflation=bestSDInflation,
MLEs=c(bestOpt$par, 0.25, muXiMLE), lambdaMLE=lambdaMLE, muZetaMLE = muZetaMLE, sigmaZetaMLE=sigmaZetaMLE, lambda0MLE=0.25,
muXiMLE=muXiMLE, logLikMLE=logLikMLE, hess=hess, optimTable=bestOptimTable)
}
# function for computing likelihood of subsidence data given GPS and subsidence data. The
# areal covariance matrix for zeta is unnecessary to input because the
# correlation matrix is loaded from memory.
# NOTE: This function assumes subsidence data is multivariate normal!
# SigmaP is the covariance matrix of the subsidence prediction data
# SigmaD is covariance matrix for the GPS and subsidence data
# SigmaPtoD is cross covariance matrix between Ypred and GPS and Yfit data
subLikGivenAll = function(params, SigmaPtoD, SigmaD, GPred=NULL, GFit=NULL, gpsDat=slipDatCSZ,
subDatPred=dr1, subDatFit=subDatPred) {
# get fit MLEs
lambda = params[1]
muZeta = params[2]
sigmaZeta = params[3]
lambda0 = params[4]
muXi = params[5]
# set other relevant parameters
# get spatial correlation parameters (computed based on fitGPSCovariance)
corPar = getCorPar()
phiZeta = corPar$phiZeta
nuZeta = corPar$nuZeta
# get data
logX = log(gpsDat$slip)
YPred = -subDatPred$subsidence
YFit = -subDatFit$subsidence
# compute inflated variance sigmaXi. Derivation from week 08_30_17.Rmd presentation.
# Transformation from additive error to multiplicative lognormal model with asympototic
# median and variance matching.
sigmaXi = sqrt(log(.5*(sqrt(4*gpsDat$slipErr^2/gpsDat$slip^2 + 1) + 1)))
# load covariance matrix of sigma over CSZ fault cells
arealCSZCor = getArealCorMat(fault)
SigmaZeta = arealCSZCor * sigmaZeta^2
# get Okada linear transformation matrix
if(is.null(GFit) || is.null(GPred)) {
nx = 300
ny= 900
lonGrid = seq(lonRange[1], lonRange[2], l=nx)
latGrid = seq(latRange[1], latRange[2], l=ny)
if(is.null(GPred))
GPred = okadaAll(csz, lonGrid, latGrid, cbind(subDatPred$Lon, subDatPred$Lat), slip=1, poisson=lambda0)
if(is.null(GFit))
GFit = okadaAll(csz, lonGrid, latGrid, cbind(subDatFit$Lon, subDatFit$Lat), slip=1, poisson=lambda0)
}
# compute taper values and G %*% T
tvec = taper(csz$depth, lambda=lambda)
GTPred = sweep(GPred, 2, tvec, "*")
GTFit = sweep(GFit, 2, tvec, "*")
# compute covariance of prediction subsidence data
subPredDistn = getSubsidenceVarianceMat(params, csz, GPred, subDat=subDatPred)
SigmaP = subPredDistn$Sigma
# calculation data and prediction means
muD = c(rep(muZeta+muXi, length(logX)), GTFit%*%rep(exp(muZeta + sigmaZeta^2/2), length(tvec)))
muP = GTPred%*%rep(exp(muZeta + sigmaZeta^2/2), length(tvec))
# compute predictive distribution of subsidence given fit data assuming
# multivariate normality
predDistn = conditionalNormal(Xd=c(logX, YFit), muD=muD, muP=muP, SigmaP=SigmaP,
SigmaD=SigmaD, SigmaPtoD=SigmaPtoD)
muc = predDistn$muc
#Sigmac = predDistn$Sigmac
# NOTE: the predictive covariance should not be the conditional
# covariance, because that represents the covariance in the mean
# rather than covariance in each individual observation. Instead,
# I use the deflated marginal variance, where the variance is
# deflated using the formula (MSE = var + bias^2). Ideally,
# the model var should be refit after assuming this conditional mean
# possibly iteratively instead of using this approximation.
varDeflation = 1 - mean((muc - muZeta)^2)/sigmaZeta^2
## compute f(Y_Pred|X,Y_Fit) (still assuming multivariate normality)
logLikPred = logLikGP(YPred - muc, chol(SigmaP * varDeflation))
logLikPred
}
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
############################################################################
# functions for performing iterative mean-parameter estimation
# fit model with nonstationary mean using iterative method and data imputation.
# params are updated (fitModelParams is called) maxIter times, and the mean is
# updated (fitModelMean is called) maxIter - 1 times. loadDat is the name of
# an RData file containing the progress of this function, and if it it included
# this function will start again from where it left off when loadDat was saved.
# saveFile is the name of the RData file to save this function's progress to.
# other inputs are inputs to doFixedFit() and updateMu() functions (niterMCMC
# is the niter input to updateMu()).
fitModelIterative = function(initParams=NULL, nsim=500, useMVNApprox=TRUE, gpsDat=slipDatCSZ,
corMatGPS=NULL, muVec=NULL, maxIter=5, fault=csz, niterMCMC=250,
loadDat=NULL, saveFile="iterFitProgress.RData", usePrior=FALSE,
subDat=dr1) {
funIns = list(initParams=initParams, nsim=nsim, useMVNApprox=useMVNApprox, gpsDat=gpsDat,
corMatGPS=corMatGPS, muVec=muVec, maxIter=maxIter, fault=fault, niterMCMC=niterMCMC)
##### Set up initial parameter guesses for the MLE optimization if necessary
if(is.null(initParams)) {
lambdaInit=2
muZetaInit = log(20)
# variance of a lognormal (x) is (exp(sigma^2) - 1) * exp(2mu + sigma^2)
# then sigma^2 = log(var(e^x)) - 2mu - log(e^(sigma^2) - 1)
# so sigma^2 \approx log(var(e^x)) - 2mu
# sigmaZetaInit = sqrt(log(var(dr1$subsidence)) - 2*muZetaInit)
sigmaZetaInit = 1
# muXiInit = log(2.25) # based on plots from exploratory analysis
initParams = c(lambdaInit, muZetaInit, sigmaZetaInit)
}
# store each updated mean and MLE sets
env = environment()
assign("muMatCSZ", matrix(nrow=nrow(fault), ncol=0), envir=env)
assign("muMatGPS", matrix(nrow=nrow(slipDatCSZ), ncol=0), envir=env)
assign("parMat", matrix(nrow=5, ncol=0), envir=env)
assign("logLiks", c(), envir=env)
# store optimization tables and other important things
assign("optimTables", list(), envir=env)
assign("lastStanResults", list(), envir=env)
assign("lastHess", c(), envir=env)
# get Okada linear transformation matrix
nx = 300
ny= 900
lonGrid = seq(lonRange[1], lonRange[2], l=nx)
latGrid = seq(latRange[1], latRange[2], l=ny)
G = okadaAll(fault, lonGrid, latGrid, cbind(subDat$Lon, subDat$Lat), slip=1, poisson=0.25)
#called maxIter times
fitModelParams = function(params, muVec=NULL, currIter=1) {
# save current progress
muMatCSZ=get("muMatCSZ", envir=env)
muMatGPS=get("muMatGPS", envir=env)
parMat=get("parMat", envir=env)
logLiks=get("logLiks", envir=env)
optimTables=get("optimTables", envir=env)
lastHess=get("lastHess", envir=env)
lastStanResults=get("lastStanResults", envir=env)
state = list(muMatCSZ=muMatCSZ, muMatGPS=muMatGPS, parMat=parMat, logLiks=logLiks,
optimTables=optimTables, lastHess=lastHess, lastStanResults=lastStanResults)
subFunName = "fitModelParams"
subFunIns = list(params=params, muVec=muVec, currIter=currIter)
save(funIns, state, subFunName, subFunIns, file=saveFile)
# base case: if past maxIter, return results
if(currIter > maxIter)
return(list(params=params, muVec=muVec))
print(paste0("fitting model parameters, current iteration is: ", currIter))
# fit the parameters
parFit = doFixedFit(params, nsim, useMVNApprox, gpsDat, corMatGPS, muVec, G=G, subDat=subDat)
# list(MLEs=c(opt$par, 0.25, muXiMLE), lambdaMLE=lambdaMLE, muZetaMLE=muZetaMLE, sigmaZetaMLE=sigmaZetaMLE, lambda0MLE=0.25,
# muXiMLE=muXiMLE, logLikMLE=logLikMLE, hess=hess, optimTable=optimTable)