-
Notifications
You must be signed in to change notification settings - Fork 5
/
CommonToAll.jl
2200 lines (2050 loc) · 81.3 KB
/
CommonToAll.jl
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
module CommonToAll
using PyPlot, StatsBase, Statistics, Distances, LinearAlgebra,
DelimitedFiles, ..AbstractOperator, NearestNeighbors, Printf,
KernelDensitySJ, KernelDensity, Interpolations, CSV, WriteVTK, Distributed
import ..Options, ..OptionsStat, ..OptionsNonstat, ..OptionsNuisance,
..history, ..GP.κ, ..calcfstar!, ..AbstractOperator.Sounding,
..AbstractOperator.getsmoothline,
..DEBUGLEVEL_TDGP
export trimxft, assembleTat1, gettargtemps, checkns, getchi2forall, nicenup, plotconv,
plot_posterior, make1Dhist, make1Dhists, setupz, zcontinue, makezρ, plotdepthtransforms,
unwrap, getn, geomprogdepth, assemblemodelsatT, getstats, gethimage,
assemblenuisancesatT, makenuisancehists, stretchexists, stepmodel,
makegrid, whichislast, makesummarygrid, makearray, plotNEWSlabels,
plotprofile, gridpoints, splitsoundingsbyline, getsoundingsperline, docontinue, linestartend,
compatidxwarn, dfn2hdr, getgdfprefix, readlargetextmatrix, pairinteractionplot, flipline,
summaryconductivity, plotsummarygrids1, getVE, writevtkfromsounding,
readcols, colstovtk, findclosestidxincolfile, zcentertoboundary, zboundarytocenter,
writeijkfromsounding, nanmean, infmean, nanstd, infstd, kde_sj, plotmanygrids, readwell,
getlidarheight, plotblockedwellonimages, getdeterministicoutputs, getprobabilisticoutputs,
readfzipped, readxyzrhoϕ
# Kernel Density stuff
abstract type KDEtype end
struct SJ <: KDEtype end
struct LSCV <: KDEtype end
function trimxft(opt::Options, burninfrac::Float64, temperaturenum::Int)
x_ft = assembleTat1(opt, :x_ftrain, burninfrac=burninfrac, temperaturenum=temperaturenum)
n = assembleTat1(opt, :nodes, burninfrac=burninfrac, temperaturenum=temperaturenum)
x, ft = zeros(size(opt.xall, 1), sum(n)), zeros(size(opt.fbounds, 1), sum(n))
nlast = 0
for (i, xft) in enumerate(x_ft)
x[:,nlast+1:nlast+n[i]] = xft[1:size(opt.xall, 1), 1:n[i]]
ft[:,nlast+1:nlast+n[i]] = xft[size(opt.xall, 1)+1:end, 1:n[i]]
nlast += n[i]
end
x, ft, n
end
function assembleTat1(optin::Options, stat::Symbol; burninfrac=0.5, temperaturenum=-1)
@assert temperaturenum!=-1 "Please explicitly specify which temperature number"
if stat == :fstar && temperaturenum!= 1
return assemblemodelsatT(optin, burninfrac=burninfrac, temperaturenum=temperaturenum)
end
isns = checkns(optin)
@assert 0.0<=burninfrac<=1.0
Tacrosschains = gettargtemps(optin)
temps = sort(unique(Tacrosschains))
niters = size(Tacrosschains, 1)
start = round(Int, niters*burninfrac)
start == 0 && (start = 1)
ttarget = temps[temperaturenum]
nmodels = sum((Tacrosschains[start:end,:] .== ttarget))
if stat == :fstar || stat == :x_ftrain
mat1 = Array{Array{Float64}, 1}(undef, nmodels)
else
mat1 = Array{Real, 1}(undef, nmodels)
end
opt = deepcopy(optin)
imodel = 0
opt.fstar_filename = "models_"*opt.fdataname*isns*".bin"
opt.x_ftrain_filename = "points_"*opt.fdataname*isns*".bin"
opt.costs_filename = "misfits_"*opt.fdataname*isns*".bin"
chain_idx = nothing
if isfile(opt.fstar_filename)
chain_idx = 1
end
for ichain in 1:size(Tacrosschains, 2)
if isnothing(chain_idx)
opt.fstar_filename = "models_"*opt.fdataname*isns*"_$ichain.bin"
opt.x_ftrain_filename = "points_"*opt.fdataname*isns*"_$ichain.bin"
opt.costs_filename = "misfits_"*opt.fdataname*isns*"_$ichain.bin"
else
chain_idx = ichain
end
if stat == :fstar
at1idx = findall(Tacrosschains[:,ichain].==ttarget) .>= start
else
at1idx = Tacrosschains[:,ichain].==ttarget
at1idx[1:start-1] .= false
end
ninchain = sum(at1idx)
(DEBUGLEVEL_TDGP > 0) && @info("chain $ichain has $ninchain models")
ninchain == 0 && continue
mat1[imodel+1:imodel+ninchain] .= history(opt, stat=stat, chain_idx=chain_idx)[at1idx]
imodel += ninchain
end
iters = history(opt, stat=:iter, chain_idx=chain_idx)
@info "obtained models $(iters[start]) to $(iters[end]) at T=$ttarget"
mat1
end
function assemblemodelsatT(opt::OptionsStat; burninfrac=0.9, temperaturenum=-1)
@assert temperaturenum!=-1 "Please explicitly specify which temperature number"
x_ft = assembleTat1(opt, :x_ftrain, burninfrac=burninfrac, temperaturenum=temperaturenum)
n = assembleTat1(opt, :nodes, burninfrac=burninfrac, temperaturenum=temperaturenum)
nmodels = length(n)
matT = Array{Array{Float64}, 1}(undef, nmodels)
K_y = zeros(opt.nmax, opt.nmax)
Kstar = zeros(Float64, size(opt.xall,2), opt.nmax)
xtest = opt.xall
for imodel = 1:nmodels
xtrain = @view x_ft[imodel][1:size(opt.xall, 1), 1:n[imodel]]
ftrain = x_ft[imodel][size(opt.xall, 1)+1:end, :]
ky = view(K_y, 1:n[imodel], 1:n[imodel])
map!(x->κ(opt.K, x),ky,pairwise(WeightedEuclidean(1 ./opt.λ² ), xtrain, dims=2))
K_y[diagind(K_y)] .+= opt.δ^2
ks = view(Kstar, :, 1:n[imodel])
map!(x->κ(opt.K, x),Kstar,pairwise(WeightedEuclidean(1 ./opt.λ² ), xtest, xtrain, dims=2))
matT[imodel] = zeros(size(opt.fbounds, 1), size(opt.xall, 2))
fstar = matT[imodel]
calcfstar!(fstar, ftrain, opt, K_y, Kstar, n[imodel])
end
matT
end
function assemblenuisancesatT(optn::OptionsNuisance;
burninfrac = 0.5, temperaturenum = -1)
@assert temperaturenum != -1 "Please specify temperature idx explicitly"
@assert 0.0 <= burninfrac < 1.0
Tacrosschains = gettargtemps(optn)
#this is probably insanely inefficient
#Θ(niters*nchains) to run the unique() call.
#however, we need to iterate over the entire array
#at some point to build the ensemble so it's
#fine. Possible improvement: store temperatures
#as the "temperature number" to start with and keep
#a separate mapping from temperature index to the float
#value. This means our sortedTs is just 1:nchains and
#also avoids any issues with equality testing of floats.
sortedTs = sort(unique(Tacrosschains))
niters = size(Tacrosschains,1)
#this will never give a bounds error
#because of the assert above
firsti = round(Int, niters*burninfrac)
firsti == 0 && (firsti = 1)
# firsti = 1 + floor(Int, niters*burninfrac)
ttarg = sortedTs[temperaturenum]
nmodels = sum(Tacrosschains[firsti:end,:] .== ttarg)
fdataname = optn.fdataname
#drop iteration number
mvals = zeros(nmodels,optn.nnu)
imodel = 0
for ichain = 1:size(Tacrosschains,2)
at1idx = Tacrosschains[:,ichain].==ttarg
at1idx[1:firsti-1] .= false
ninchain = sum(at1idx)
(DEBUGLEVEL_TDGP > 0) && @info("chain $ichain has $ninchain models")
ninchain == 0 && continue
vals_filename = "values_nuisance_"*fdataname*".bin"
if isfile(vals_filename)
nraw = readdlm(vals_filename, ' ', String)
cids = parse.(Int, nraw[:,1])
ndat = parse.(Float64, nraw[cids .== ichain, 3:end])
else
vals_filename = "values_nuisance_"*fdataname*"$ichain.bin"
ndat = readdlm(vals_filename, ' ', Float64)[:,2:end]
end
mvals[imodel+1:imodel+ninchain,:] .= ndat[at1idx,:]
imodel += ninchain
end
mvals
end
function getnchains(costs_filename)
if isfile(costs_filename*".bin")
data = readdlm(costs_filename * ".bin", String)
chids = parse.(Int, data[:,1])
return maximum(chids)
end
c = 0
r = Regex(costs_filename)
for fname in readdir(pwd())
c += !isa(match(r, fname), Nothing)
end
c
end
function gettargtemps(opt_in::Options)
isns = checkns(opt_in)
opt = deepcopy(opt_in)
costs_filename = "misfits_"*opt.fdataname*isns
nchains = getnchains(costs_filename)
@info "Number of chains is $nchains"
# now look at any chain to get how many iterations
multichainfile = nothing
if isfile(costs_filename*".bin")
opt.costs_filename = costs_filename*".bin"
multichainfile = 1 # set if all chains are in one file
else
opt.costs_filename = costs_filename*"_1.bin"
end
iters = history(opt, stat=:iter, chain_idx=multichainfile)
niters = length(iters)
@info "McMC has run for $(iters[end]) iterations"
# then create arrays of unsorted by temperature T
Tacrosschains = zeros(Float64, niters, nchains)
# get the values into the arrays
for ichain in 1:nchains
if isnothing(multichainfile)
opt.costs_filename = costs_filename*"_$ichain.bin"
Tacrosschains[:,ichain] = history(opt, stat=:T)
else
Tacrosschains[:,ichain] = history(opt, stat=:T, chain_idx=ichain)
end
end
Tacrosschains
end
function gettargtemps(optn_in::OptionsNuisance)
optn = deepcopy(optn_in)
costs_filename = "misfits_"*optn.fdataname*"nuisance"
nchains = getnchains(costs_filename)
@info "Number of chains is $nchains"
multichainfile = nothing
if isfile(costs_filename*".bin")
optn.costs_filename = costs_filename*".bin"
multichainfile = 1 # set if all chains are in one file
else
optn.costs_filename = costs_filename*"_1.bin"
end
iters = history(optn, stat=:iter, chain_idx=multichainfile)
niters = length(iters)
@info "MCMC has run for $(iters[end]) iterations"
Tacrosschains = zeros(Float64, niters, nchains)
for ichain in 1:nchains
if isnothing(multichainfile)
optn.costs_filename = costs_filename*"_$ichain.bin"
Tacrosschains[:,ichain] = history(optn, stat=:T)
else
Tacrosschains[:,ichain] = history(optn, stat=:T, chain_idx=ichain)
end
end
Tacrosschains
end
function getstats(optin::Options;
figsize=(5,6), fontsize=12,
nxticks=5, nyticks=5, alpha=0.6)
isns = checkns(optin)
opt = deepcopy(optin)
costs_filename = "misfits_"*opt.fdataname*isns
nchains = getnchains(costs_filename)
chains = 1:nchains
@info "Number of chains is $nchains"
multichainfile = nothing
if isfile(costs_filename*".bin")
opt.costs_filename = costs_filename*".bin"
multichainfile = 1
else
opt.costs_filename = costs_filename*"_1.bin"
end
iters = history(opt, stat=:iter, chain_idx=multichainfile)
statnames = [:acceptanceRateBirth, :acceptanceRateDeath,
:acceptanceRatePosition, :acceptanceRateProperty, :acceptanceRateDC]
f,ax = plt.subplots(length(statnames), 1,
sharex=true, sharey=true, figsize=figsize)
maxar = 0
for (ichain, chain) in enumerate(chains)
if isnothing(multichainfile)
opt.costs_filename = costs_filename*"_$chain.bin"
chain_idx = nothing
else
chain_idx = ichain
end
for (istat, statname) in enumerate(statnames)
ar = history(opt, stat=statname, chain_idx=chain_idx)
mx = maximum(ar[.!isnan.(ar)])
mx > maxar && (maxar = mx)
ax[istat].plot(iters, ar, alpha=alpha)
if ichain == nchains
ax[istat].set_title("$statname "*isns)
ax[istat].set_ylabel("acc. %")
if istat == length(statnames)
ax[istat].set_xlabel("mcmc step no.")
ax[istat].set_xticks(LinRange(iters[1], iters[end], nxticks))
ax[istat].set_xlim(extrema(iters))
ax[istat].set_yticks(LinRange(0, maxar, nyticks))
ax[istat].set_ylim(0, maxar)
end
end
end
end
nicenup(f, fsize=fontsize)
end
function getstats(optin::OptionsNuisance;
figsize=(5,6), fontsize=12,
nxticks=5, nyticks=5, alpha=0.6)
opt = deepcopy(optin)
costs_filename = "misfits_"*opt.fdataname*"nuisance"
nchains = getnchains(costs_filename)
chains = 1:nchains
@info "Number of chains is $nchains"
multichainfile = nothing
if isfile(costs_filename*".bin")
opt.costs_filename = costs_filename*".bin"
multichainfile = 1
else
opt.costs_filename = costs_filename*"_1.bin"
end
iters = history(opt, stat=:iter, chain_idx=multichainfile)
statname = :acceptanceRate
f,ax = plt.subplots(length(optin.idxnotzero), 1, sharex=true, sharey=true, figsize=figsize)
maxar = 0
for (ichain, chain) in enumerate(chains)
if isnothing(multichainfile)
opt.costs_filename = costs_filename*"_$chain.bin"
chain_idx = nothing
else
chain_idx = ichain
end
ar = history(opt, stat=statname, chain_idx=chain_idx)[:,optin.idxnotzero]
for (i, idx) in enumerate(optin.idxnotzero)
mx = maximum(ar[.!isnan.(ar)])
mx > maxar && (maxar = mx)
ax[i].plot(iters, ar[:,i], alpha=alpha)
if ichain == nchains
ax[i].set_title("Nuisance #$idx")
ax[i].set_ylabel("acc. %")
if i == length(optin.idxnotzero)
ax[i].set_xlabel("mcmc step no.")
ax[i].set_xticks(LinRange(iters[1], iters[end], nxticks))
ax[i].set_xlim(extrema(iters))
end
end
end
end
nicenup(f, fsize=fontsize)
end
function checkns(optin::Options)
isns = typeof(optin) == OptionsNonstat
(DEBUGLEVEL_TDGP > 0) && @info("ns is $isns")
ns = "ns"
isns || (ns="s")
return ns
end
function getchi2forall(optn_in::OptionsNuisance;
nchains = 1,
figsize = (6,4),
fsize = 8,
alpha = 0.25,
nxticks = 0,
gridon = false)
optn = deepcopy(optn_in)
fdataname = optn.fdataname
costs_filename = "misfits_"*fdataname*"nuisance"
if nchains == 1
nchains = getnchains(costs_filename)
end
optn.costs_filename = costs_filename*"_1.bin"
multichainfile = false
if isfile(optn.costs_filename)
iters = history(optn, stat=:iter)
else
multichainfile = true
optn.costs_filename = costs_filename*".bin"
iters = history(optn, stat=:iter, chain_idx=1)
end
niters = length(iters)
Tacrosschains = zeros(Float64, niters, nchains)
χ2acrosschains = zeros(Float64, niters, nchains)
chain_idx = nothing
for chain in 1:nchains
if multichainfile
chain_idx = ichain
else
optn.costs_filename = costs_filename*"_$(chain).bin"
end
Tacrosschains[:,chain] = history(optn, stat=:T, chain_idx=chain_idx)
χ2acrosschains[:,chain] = history(optn, stat=:misfit, chain_idx=chain_idx)
end
Torder = sort([(i,j) for i=1:niters, j=1:nchains],
by = ix->Tacrosschains[ix...],
dims = 2)
χ2sorted = [χ2acrosschains[Torder[i,j]...] for i=1:niters, j=1:nchains]
fig, ax = subplots(3,1, sharex=true, figsize=figsize)
ax[1].plot(iters, χ2acrosschains, alpha=alpha)
ax[1].set_xlim(extrema(iters)...)
ax[1].set_ylim(0,100)
ax[1].set_title("unsorted χ^2 misfit")
ax[2].plot(iters, Tacrosschains, alpha=alpha)
ax[2].set_title("temperature")
ax[3].plot(iters, χ2sorted, alpha=alpha)
ax[3].set_ylim(0,100)
ax[3].set_title("sorted χ^2 misfit")
ax[3].set_xlabel("iterations")
nxticks == 0 || ax[3].set_xticks(iters[1]:div(iters[end],nxticks):iters[end])
nicenup(fig, fsize = fsize)
end
function getchi2forall(opt_in::Options;
nchains = 1,
figsize = (6,4),
fsize = 8,
alpha = 0.5,
nxticks = 0,
gridon = false,
omittemp = false,
hidetitle = true,
)
# now look at any chain to get how many iterations
isns = checkns(opt_in)
opt = deepcopy(opt_in)
costs_filename = "misfits_"*opt.fdataname*isns
if nchains == 1 # then actually find out how many chains there are saved
nchains = getnchains(costs_filename)
end
opt.costs_filename = costs_filename*"_1.bin"
multichainfile = false
if isfile(opt.costs_filename)
iters = history(opt, stat=:iter)
else
opt.costs_filename = costs_filename*".bin"
iters = history(opt, stat=:iter, chain_idx=1)
multichainfile=true
end
niters = length(iters)
# then create arrays of unsorted by temperature T, k, and chi2
Tacrosschains = zeros(Float64, niters, nchains)
kacrosschains = zeros(Int, niters, nchains)
X2by2inchains = zeros(Float64, niters, nchains)
# get the values into the arrays
chain_idx = nothing
for ichain in 1:nchains
if multichainfile
chain_idx = ichain
else
opt.costs_filename = costs_filename*"_$ichain.bin"
end
Tacrosschains[:,ichain] = history(opt, stat=:T, chain_idx=chain_idx)
kacrosschains[:,ichain] = history(opt, stat=:nodes, chain_idx=chain_idx)
X2by2inchains[:,ichain] = history(opt, stat=:U, chain_idx=chain_idx)
end
if !hidetitle # then we are usually not interested in the temperature sorting of chains
f, ax = plt.subplots(3,1, sharex=true, figsize=figsize)
ax[1].plot(iters, kacrosschains, alpha=alpha)
ax[1].set_xlim(extrema(iters)...)
ax[1].set_title(isns*" unsorted by temperature")
gridon && ax[1].grid()
ax[1].set_ylabel("# nodes")
ax[2].plot(iters, X2by2inchains, alpha=alpha)
gridon && ax[2].grid()
ax[2].set_ylabel("-Log L")
gridon && ax[3].grid()
ax[3].plot(iters, Tacrosschains, alpha=alpha)
ax[3].set_ylabel("Temperature")
ax[3].set_xlabel("iterations")
nxticks == 0 || ax[3].set_xticks(iters[1]:div(iters[end],nxticks):iters[end])
nicenup(f, fsize=fsize)
end
Tunsorted = copy(Tacrosschains)
for jstep = 1:niters
sortidx = sortperm(vec(Tacrosschains[jstep,:]))
X2by2inchains[jstep,:] = X2by2inchains[jstep,sortidx]
kacrosschains[jstep,:] = kacrosschains[jstep,sortidx]
Tacrosschains[jstep,:] = Tacrosschains[jstep,sortidx]
end
nrows = omittemp ? 2 : 3
f, ax = plt.subplots(nrows, 1, sharex=true, figsize=figsize)
nchainsatone = sum(Tacrosschains[1,:] .== 1)
ax[1].plot(iters, kacrosschains, alpha=alpha)
ax[1].set_xlim(extrema(iters)...)
ax[1].set_ylabel("# nuclei")
!hidetitle && ax[1].set_title(isns*" sorted by temperature")
ax[1].plot(iters, kacrosschains[:,1:nchainsatone], "k", alpha=alpha)
gridon && ax[1].grid()
chi2low, chi2high = 0.01*median(X2by2inchains[:,1]), 5*median(X2by2inchains[:,end])
ax[2].plot(iters, X2by2inchains, alpha=alpha)
ax[2].plot(iters, X2by2inchains[:,1:nchainsatone], "k", alpha=alpha)
ax[2].set_ylabel("-Log L")
ax[2].set_ylim(chi2low, chi2high)
gridon && ax[2].grid()
if !omittemp
ax[3].plot(iters, Tunsorted, alpha=alpha, color="gray")
ax[3].set_ylabel("Temperature")
gridon && ax[3].grid()
end
nxticks == 0 || ax[3].set_xticks(iters[1]:div(iters[end],nxticks):iters[end])
ax[nrows].set_xlabel("iterations")
nicenup(f, fsize=fsize)
end
function plotconv(optin::Options; burninfrac= 0.5, first=0.1, last=0.5, till=1.0, figsize=(6,2), fontsize=10, nbins=50, doall=false)
opt = deepcopy(optin)
iter, k, chi2by2 = map(x->assembleTat1(opt, x; temperaturenum=1, burninfrac), (:iter, :nodes, :U))
idx = sortperm(iter)
till = round(Int, idx[end]*till)
iter, k, chi2by2 = map(x->x[idx][1:till], (iter, k, chi2by2))
f, ax = plt.subplots(1, 2; figsize)
# first group, second group
getconv(ax, iter, chi2by2, k, nbins, opt.nmin, opt.nmax, first, last)
ax[1].set_xlabel("-ve log likelihood")
ax[1].set_ylabel("pdf")
ax[2].set_xlabel("# nuclei")
ax[2].set_ylabel("pdf")
nicenup(f, fsize=fontsize)
nothing
end
function getconv(ax, iter, chi2by2, k, nbins, nmin, nmax, first, last)
first, last = map(x->round(Int, length(iter)*x), (first, last))
plotconv(ax, chi2by2[1:first], k[1:first], nbins, nmin, nmax)
plotconv(ax, chi2by2[last:end], k[last:end], nbins, nmin, nmax)
end
function plotconv(ax, chi2by2, k, nbins, nmin, nmax)
kdefunc_nll = kde_(SJ(), chi2by2)
nllrange = range(minimum(chi2by2), maximum(chi2by2), nbins)
krange = nmin-0.5:1:nmax+0.5
ax[1].plot(nllrange, kdefunc_nll(nllrange))
ax[2].hist(k, krange, density=true, histtype="step")
end
function geomprogdepth(n, dy, c)
dy*(1.0-c^n)/(1-c)
end
function getn(z, dy, c)
log(1 - z/dy*(1-c))/log(c)
end
function unwrap(v, inplace=false)
# currently assuming an array
unwrapped = inplace ? v : copy(v)
for i in 2:length(v)
while unwrapped[i] - unwrapped[i-1] >= pi
unwrapped[i] -= 2pi
end
while unwrapped[i] - unwrapped[i-1] <= -pi
unwrapped[i] += 2pi
end
end
return unwrapped
end
function setupz(zstart, extendfrac;n=100, dz=10, showplot=false, forextension=false)
@assert extendfrac>1
znrange = 1.0:n
zboundaries = [zstart, zstart .+ geomprogdepth.(znrange, dz, extendfrac)...]
thickness = diff(zboundaries)
zall = zboundaries[1:end-1] + thickness/2
znall = getn.(zall .- zstart, dz, extendfrac)
showplot && plotdepthtransforms(zall, znall, zboundaries)
zbreturn = forextension ? zboundaries : zboundaries[1:end-1]
return zall, znall, zbreturn
end
function zcontinue(;zall=nothing, znall=nothing, zboundaries=nothing, n=nothing,
extendfrac=nothing, dz=nothing, showplot=false)
isa(dz, Nothing) && (dz=diff(zboundaries)[end])
zall_, znall_, zboundaries_ = setupz(zboundaries[end], extendfrac, n=n, dz=dz, showplot=false)
zall, znall, zboundaries = [zall;zall_], [znall; znall[end] .+ znall_], [zboundaries[1:end-1]; zboundaries_]
zlast = zboundaries[end] + diff(zboundaries)[end]
showplot && plotdepthtransforms(zall, znall, [zboundaries;zlast])
@assert all(diff(zall).>0)
@assert all(diff(znall).>0)
@assert all(diff(zboundaries).>0)
zall, znall, zboundaries
end
function setupz(zstart;n=100, dz=10)
zboundaries = range(zstart, step=dz, length=n)
zall = zboundaries[1:end-1] .+ dz/2
znall = 1.5:1:n-0.5
plotdepthtransforms(zall, znall, zboundaries)
return zall, znall, zboundaries[1:end-1]
end
function plotdepthtransforms(zall, znall, zboundaries; fontsize=12)
thickness = diff(zboundaries)
f, ax = plt.subplots(2, 2, sharex="col", sharey="row", figsize=(8,5))
ax[1].stem(zboundaries[1:end-1], zboundaries[1:end-1], markerfmt="")
ax[1].stem(zall, zall, "k--", markerfmt=" ")
ax[1].set_ylabel("depth m")
ax[2].stem(zall,thickness, "k--", markerfmt=" ")
ax[2].set_ylabel("thickness m")
ax[2].set_xlabel("depth m")
ax[2].yaxis.grid(which="major")
ax[3].plot(znall, zall)
ax[3].grid()
ax[4].stem(znall,thickness, "k--", markerfmt=" ")
ax[4].set_xlabel("depth index")
ax[4].yaxis.grid(which="major")
plt.suptitle("Forward model discretization"; fontsize)
nicenup(f, fsize=fontsize)
end
function makezρ(zboundaries::Array{Float64, 1};
zfixed = [-1e6, 0.],
ρfixed = [1e12 0.3])
@assert length(zfixed) == length(ρfixed)
z = [zfixed..., zboundaries...]
@assert all(diff(z).>0)
ρ = zeros(length(z))
nfixed = length(ρfixed)
ρ[1:nfixed] .= ρfixed
z, ρ, nfixed
end
function nicenup(g::PyPlot.Figure;fsize=12, h_pad=nothing, increasefraction=1.2, minsize=true)
for ax in g.axes
if !isempty(ax.get_yticklabels())
fs = ax.get_yticklabels()[1].get_fontsize()
ns = getnewfontsize(fs, increasefraction, fsize; minsize)
ax.tick_params("both", labelsize=ns)
elseif !isempty(ax.get_xticklabels())
fs = ax.get_xticklabels()[1].get_fontsize()
ns = getnewfontsize(fs, increasefraction, fsize; minsize)
ax.tick_params("both", labelsize=ns)
end
xlh, ylh, tlh = ax.xaxis.label, ax.yaxis.label, ax.title
for h in (xlh, ylh, tlh)
fs = h.get_fontsize()
ns = getnewfontsize(fs, increasefraction, fsize; minsize)
h.set_fontsize(ns)
end
if any(keys(ax) .== :zaxis)
fs = ax.zaxis.label.get_fontsize()
ns = getnewfontsize(fs, increasefraction, fsize; minsize)
ax.zaxis.label.set_fontsize(ns)
end
if typeof(ax.get_legend_handles_labels()[1]) != Array{Any,1}
ax.legend(loc="best", fontsize=fsize)
fs = ax.get_legend().get_texts()[1].get_fontsize()
ns = getnewfontsize(fs, increasefraction, fsize; minsize)
ax.legend(loc="best", fontsize=ns)
end
end
if isnothing(h_pad)
g.tight_layout()
else
g.tight_layout(;h_pad)
end
end
function getnewfontsize(fs, increasefraction, fsize; minsize=true)
if minsize
ns = fs*increasefraction
ns = ns > fsize ? ns : fsize
else #exactsize
ns = fsize
end
end
function plot_posterior(F::Operator1D,
optns::OptionsNonstat,
opts::OptionsStat;
temperaturenum = 1,
nbins = 50,
burninfrac=0.5,
qp1=0.05,
qp2=0.95,
vmaxpc=1.0,
cmappdf = "inferno",
figsize=(10,5),
pdfnormalize=false,
fsize=14,
istothepow=false,
usekde = false,
kdetype = SJ(),
alpha=0.25,
lw = 1)
@assert 0<vmaxpc<=1
M = assembleTat1(optns, :fstar, burninfrac=burninfrac, temperaturenum=temperaturenum)
himage_ns, edges_ns, CI_ns, = gethimage(F, M, optns; temperaturenum=temperaturenum,
nbins=nbins, qp1=qp1, qp2=qp2, istothepow=istothepow, usekde, kdetype,
islscale=false, pdfnormalize=pdfnormalize)
M = assembleTat1(opts, :fstar, burninfrac=burninfrac, temperaturenum=temperaturenum)
himage, edges, CI, = gethimage(F, M, opts; temperaturenum=temperaturenum,
nbins=nbins, qp1=qp1, qp2=qp2, istothepow=false, usekde, kdetype,
islscale=true, pdfnormalize=pdfnormalize)
f,ax = plt.subplots(1, 2, sharey=true, figsize=figsize)
xall = opts.xall
xmesh = [zcentertoboundary(xall); xall[end]]
vmin, vmax = extrema(himage_ns)
vmax = vmin+vmaxpc*(vmax-vmin)
im1 = ax[1].pcolormesh(edges_ns[:], xmesh, himage_ns, cmap=cmappdf, vmax=vmax)
cb1 = colorbar(im1, ax=ax[1])
cb1.ax.set_xlabel("pdf \nns")
propmin, propmax = getbounds(CI_ns, optns.fbounds)
ax[1].set_xlim(propmin, propmax)
vmin, vmax = extrema(himage)
vmax = vmin+vmaxpc*(vmax-vmin)
im2 = ax[2].pcolormesh(edges[:], xmesh, himage, cmap=cmappdf, vmax=vmax)
ax[2].set_ylim(extrema(xall)...)
propmin, propmax = getbounds(CI, opts.fbounds)
ax[2].set_xlim(propmin, propmax)
ax[2].invert_yaxis()
cb2 = colorbar(im2, ax=ax[2])
cb2.ax.set_xlabel("pdf \nstationary")
ax[1].plot(CI_ns, xall[:], linewidth=lw, color="w"; alpha)
ax[2].plot(CI, xall[:], linewidth=lw, color="w"; alpha)
ax[1].set_xlabel(L"\log_{10} \rho")
ax[1].set_ylabel("depth (m)")
ax[2].set_xlabel(L"\log_{10} λ")
nicenup(f, fsize=fsize)
end
function plot_posterior(F::Operator1D,
opt::OptionsStat;
useoptfbounds = true,
temperaturenum = 1,
nbins = 50,
burninfrac=0.5,
qp1=0.05,
qp2=0.95,
vmaxpc=1.0,
cmappdf = "inferno",
figsize=(5,5),
pdfnormalize=false,
istothepow=false,
fsize=14,
plotCI = true,
plotmean = true,
alpha = 1.0,
CIcolor = ["w", "k"],
meancolor = ["m", "r"],
lwidth = 2,
pdfclim = nothing,
showslope = false,
kdetype = SJ(),
usekde = false,
doplot = true)
@assert 0<vmaxpc<=1
if useoptfbounds
if stretchexists(F)
rhomin, rhomax = minimum(F.low), maximum(F.low + F.Δ)
else
rhomin, rhomax = extrema(opt.fbounds)
end
else
rhomin, rhomax = Inf, -Inf
end
M = assembleTat1(opt, :fstar, burninfrac=burninfrac, temperaturenum=temperaturenum)
himage, edges, CI, meanimage, meandiffimage, sdslope, = gethimage(F, M, opt; temperaturenum,
nbins, qp1, qp2, istothepow, rhomin, rhomax, usekde, kdetype,
islscale=false, pdfnormalize=pdfnormalize)
if doplot
if showslope
f, ax = plt.subplots(1,2, sharey=true, figsize=figsize)
else
f, ax = plt.subplots(1,1, sharey=true, figsize=figsize, squeeze=false)
end
xall = opt.xall
xmesh = [zcentertoboundary(xall); xall[end]]
vmin, vmax = extrema(himage)
vmax = vmin+vmaxpc*(vmax-vmin)
im1 = ax[1].pcolormesh(edges[:], xmesh, himage, cmap=cmappdf, vmax=vmax)
ax[1].set_ylim(extrema(xall)...)
ax[1].invert_yaxis()
plotCI && ax[1].plot(CI, xall[:], linewidth=lwidth, color=CIcolor[1], alpha=alpha)
plotCI && ax[1].plot(CI, xall[:], linewidth=lwidth, color=CIcolor[2], linestyle="--", alpha=alpha)
plotmean && ax[1].plot(meanimage[:], xall[:], linewidth=lwidth, color=meancolor[1], alpha=alpha)
plotmean && ax[1].plot(meanimage[:], xall[:], linewidth=lwidth, color=meancolor[2], linestyle="--", alpha=alpha)
ax[1].set_xlabel(L"\log_{10} \rho")
ax[1].set_ylabel("depth (m)")
bounds = copy(opt.fbounds)
if stretchexists(F)
bounds = [minimum(F.low) maximum(F.low + F.Δ)]
end
istothepow && (bounds .= 10 .^ bounds)
propmin, propmax = getbounds(CI, bounds)
ax[1].set_xlim(propmin, propmax)
cb1 = colorbar(im1, ax=ax[1])
cb1.ax.set_title("pdf")
if showslope
ax[2].plot(meandiffimage[:], xall[:], linewidth=2, color="k", linestyle="-")
zeroside = meandiffimage[:]-sdslope[:]
zeroside[zeroside .< 0] .= 0
ax[2].fill_betweenx(xall[:],zeroside,meandiffimage[:]+sdslope[:],alpha=.25)
ax[2].set_xlabel("mean slope")
end
!isnothing(pdfclim) && ax[1].collections[1].set_clim(pdfclim)
nicenup(f, fsize=fsize)
end
CI[:,1], CI[:,2], CI[:,3], meanimage, meandiffimage, sdslope
end
function getbounds(CI, bounds)
propmin = min(minimum(CI), minimum(bounds))
propmax = max(maximum(CI), maximum(bounds))
propmin, propmax
end
function plot_posterior(operator::Operator1D,
optn::OptionsNuisance;
temperaturenum = 1,
nbins = 50,
burninfrac=0.5,
figsize=(5,8),
pdfnormalize=false,
fsize=10,
qp1 = 0.05,
qp2 = 0.95,
labels= nothing,
doplot=true)
hists, CI = makenuisancehists(optn, qp1, qp2, burninfrac = burninfrac,
nbins = nbins, temperaturenum = temperaturenum,
)
if doplot
fig,ax = subplots(length(hists), 1, figsize=figsize, squeeze=false)
for (i, h) = enumerate(hists)
bwidth, bx, denom = getbinsfromhist(h, pdfnormalize=pdfnormalize)
ax[i].bar(bx, h.weights./denom, width=bwidth, edgecolor="black")
!isnothing(labels) && ax[i].set_xlabel(labels[i])
ax[i].set_ylabel("pdf")
end
nicenup(fig, fsize=fsize)
end
hists, CI
end
function getbinsfromhist(h, ;pdfnormalize=false)
bwidth = diff(h.edges[1])
bx = h.edges[1][1:end-1] + bwidth/2
denom = pdfnormalize ? maximum(h.weights) : sum(h.weights)*bwidth
bwidth, bx, denom
end
function makenuisancehists(optn::OptionsNuisance, qp1, qp2; burninfrac = 0.5, nbins = 50,
temperaturenum = -1)
@assert temperaturenum != -1 "Please explicitly specify the temperature index"
nuisanceatT = assemblenuisancesatT(optn, burninfrac = burninfrac,
temperaturenum = temperaturenum)
nnu = length(optn.idxnotzero)
CI = zeros(Float64, nnu, 3)
h = Vector{Histogram}(undef, nnu)
for (i, islice) in enumerate(optn.idxnotzero)
numin, numax = extrema(optn.bounds[islice,:])
edges = LinRange(numin, numax, nbins+1)
h[i] = fit(Histogram, nuisanceatT[:,islice], edges)
CI[i,:] = quantile(nuisanceatT[:,islice], [qp1, 0.5, qp2])
end
h, CI
end
function firstderiv(x)
fd = similar(x)
fd[1] = x[2] - x[1]
fd[end] = x[end] - x[end-1]
fd[2:end-1] .= (x[3:end] - x[1:end-2])/2
abs.(fd)
# fd
end
function secondderiv(x)
sd = similar(x)
sd[1] = 2x[1] - 5x[2] + 4x[3] - x[4]
sd[2:end-1] .= (x[3:end] - x[2:end-1] + x[1:end-2])
sd[end] = 2x[end] - 5x[end-1] + 4x[end-2] - x[end-3]
abs.(sd)
end
function dodensityestimate(usekde::Bool, data, K::KDEtype, edges)
if usekde
kdefunc = kde_(K, data)
kdefunc(0.5(edges[2:end]+edges[1:end-1]))
else
w = fit(Histogram, data, edges).weights
w/(sum(w)*diff(edges)[1])
end
end
function stretchexists(F::Operator)
in(:stretch, fieldnames(typeof(F))) && F.stretch
end
kde_(K::SJ, data) = kde_sj(;data)
kde_(K::LSCV, data) = kde_cv(;data)
abstract type KDEstimator end
# Sheather-Jones plugin
struct kde_sj <: KDEstimator
data
bw :: Real
end
kde_sj(;data=zeros(0)) = kde_sj(data, bwsj(data))
function (foo::kde_sj)(xvals)
density(foo.data, foo.bw, xvals)
end
function kde_sj(x; npoints=40)
points = range(extrema(x)...,length=npoints)
datapdf = kde_sj(data=x)
datapdf(points), points
end
# LSCV KDE
struct kde_cv <: KDEstimator
U
end
kde_cv(;data=zeros(0)) = kde_cv(kde_lscv(data))
function (foo::kde_cv)(xvals)
pdf(foo.U, xvals)
end
function gethimage(F::Operator, M::AbstractArray, opt::Options;
burninfrac = 0.5,
nbins = 50,
rhomin=Inf,
rhomax=-Inf,
qp1=0.05,
qp2=0.95,
islscale = false,
pdfnormalize=false,
istothepow = false,
usekde = false,
kdetype = SJ(),
temperaturenum=1)
T = x->x
if (rhomin == Inf) && (rhomax == -Inf)
if !stretchexists(F) # if no stretch
for (i,mm) in enumerate(M)
rhomin_mm = minimum(mm)
rhomax_mm = maximum(mm)
rhomin_mm < rhomin && (rhomin = rhomin_mm)
rhomax_mm > rhomax && (rhomax = rhomax_mm)
end
if (typeof(opt) == OptionsStat && opt.needλ²fromlog) && islscale
T = x->0.5log10(x)
end
else # there is a stretch
rhomin = minimum(F.low)
rhomax = maximum(F.low + F.Δ)
end
else
@assert rhomin < rhomax
end
if istothepow && !islscale
T = x->10. ^x
end
rhomin, rhomax = map(x->T(x), (rhomin, rhomax))
edges = LinRange(rhomin, rhomax, nbins+1)
himage = zeros(Float64, length(M[1]), nbins)
CI = zeros(Float64, length(M[1]), 3)
meanimage = zeros(length(M[1]))
for ilayer=1:length(M[1])
if !stretchexists(F) # if no stretch
mthislayer = [T(m[ilayer]) for m in M]
himage[ilayer,:] = dodensityestimate(usekde, mthislayer, kdetype, edges)
CI[ilayer,:] = [quantile(mthislayer,(qp1, 0.5, qp2))...]
meanimage[ilayer] = mean(vec(mthislayer))
else # there is an affine stretch with depth
mthislayer = [m[ilayer] for m in M]
expandedthislayer = T.(F.low[ilayer] .+ mthislayer*F.Δ[ilayer])
himage[ilayer,:] = dodensityestimate(usekde, expandedthislayer, kdetype, edges)
CI[ilayer,:] = [quantile(expandedthislayer,(qp1, 0.5, qp2))...]
meanimage[ilayer] = mean(vec(expandedthislayer))
end
pdfnormalize && (himage[ilayer,:] = himage[ilayer,:]/maximum(himage[ilayer,:]))
end
if !stretchexists(F)
Tm = [T.(m) for m in M]
else
Tm = [T.(F.low + vec(m).*F.Δ) for m in M]
end
Mslope = mean(firstderiv.(Tm))
sdevslope = std(firstderiv.(Tm))
himage, edges, CI, meanimage, Mslope, sdevslope
end
# some plotting codes for AEM
function stepmodel(ax, iaxis, color, ρ , aem, model_lw, alpha)
nfixed = aem.nfixed
if isnothing(color)
ax[iaxis].step(ρ, aem.z[nfixed+1:end], linewidth=model_lw, alpha=alpha)
else
ax[iaxis].step(ρ, aem.z[nfixed+1:end]; linewidth=model_lw, alpha=alpha, color)
end
end
function splitsoundingsbyline(soundings::Array{S, 1}) where S<:Sounding
alllines = [s.linenum for s in soundings]
linenum = unique(alllines)
nlines = length(linenum)
linestartidx = zeros(Int, nlines)
for i = 1:nlines
linestartidx[i] = findfirst(alllines .== linenum[i])
end
linestartidx
end