-
Notifications
You must be signed in to change notification settings - Fork 2
/
ptBayeslands_sedvec.py
1587 lines (1116 loc) · 63.1 KB
/
ptBayeslands_sedvec.py
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
#Main Contributers: Rohitash Chandra and Ratneel Deo Email: [email protected], [email protected]
# Bayeslands II: Parallel tempering for multi-core systems - Badlands
from __future__ import print_function, division
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import multiprocessing
import numpy as np
import random
import time
import operator
import math
import cmocean as cmo
from pylab import rcParams
import copy
from copy import deepcopy
import cmocean as cmo
from pylab import rcParams
import collections
from scipy import special
import fnmatch
import shutil
from PIL import Image
from io import StringIO
from cycler import cycler
import os
import sys
import matplotlib.mlab as mlab
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from scipy.spatial import cKDTree
from scipy import stats
from pyBadlands.model import Model as badlandsModel
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.mplot3d import Axes3D
import itertools
import plotly
import plotly.plotly as py
from plotly.graph_objs import *
plotly.offline.init_notebook_mode()
from plotly.offline.offline import _plot_html
import pandas
import argparse
#Initialise and parse inputs
parser=argparse.ArgumentParser(description='PTBayeslands modelling')
parser.add_argument('-p','--problem', help='Problem Number 1-crater-fast,2-crater,3-etopo-fast,4-etopo,5-null,6-mountain', required=True, dest="problem",type=int)
parser.add_argument('-s','--samples', help='Number of samples', default=10000, dest="samples",type=int)
parser.add_argument('-r','--replicas', help='Number of chains/replicas, best to have one per availble core/cpu', default=10,dest="num_chains",type=int)
parser.add_argument('-t','--temperature', help='Demoninator to determine Max Temperature of chains (MT=no.chains*t) ', default=10,dest="mt_val",type=int)
parser.add_argument('-swap','--swap', help='Swap Ratio', dest="swap_ratio",default=0.02,type=float)
parser.add_argument('-b','--burn', help='How many samples to discard before determing posteriors', dest="burn_in",default=0.25,type=float)
parser.add_argument('-pt','--ptsamples', help='Ratio of PT vs straight MCMC samples to run', dest="pt_samples",default=0.5,type=float)
parser.add_argument('-step','--step', help='Step size for proposals (0.02, 0.05, 0.1 etc)', dest="step_size",default=0.05,type=float)
args = parser.parse_args()
#parameters for Parallel Tempering
problem = args.problem
samples = args.samples #10000 # total number of samples by all the chains (replicas) in parallel tempering
num_chains = args.num_chains
swap_ratio = args.swap_ratio
burn_in=args.burn_in
#maxtemp = int(num_chains * 5)/args.mt_val
maxtemp = args.mt_val
swap_interval = int(swap_ratio * (samples/num_chains)) #how ofen you swap neighbours
num_successive_topo = 4
pt_samples = samples*args.pt_samples # portion of PT to be executed, then leftover is MCMC on parallel cores
step_size = args.step_size
class ptReplica(multiprocessing.Process):
def __init__(self, num_param, vec_parameters, minlimits_vec, maxlimits_vec, stepratio_vec, check_likelihood_sed , swap_interval, sim_interval, simtime, samples, real_elev, real_erodep_pts, erodep_coords, filename, xmlinput, run_nb, tempr, parameter_queue,event , main_proc, burn_in):
multiprocessing.Process.__init__(self)
self.processID = tempr
self.parameter_queue = parameter_queue
self.event = event
self.signal_main = main_proc
self.temperature = tempr
self.swap_interval = swap_interval
self.filename = filename
self.input = xmlinput
self.simtime = simtime
self.samples = samples
self.run_nb = run_nb
self.num_param = num_param
self.font = 9
self.width = 1
self.vec_parameters = np.asarray(vec_parameters)
self.minlimits_vec = np.asarray(minlimits_vec)
self.maxlimits_vec = np.asarray(maxlimits_vec)
self.stepratio_vec = np.asarray(stepratio_vec)
self.check_likelihood_sed = check_likelihood_sed
self.real_erodep_pts = real_erodep_pts
self.erodep_coords = erodep_coords
self.real_elev = real_elev
self.runninghisto = True
self.burn_in = burn_in
self.sim_interval = sim_interval
self.sedscalingfactor = 50 # this is to ensure that the sediment likelihood is given more emphasis as it considers fewer points (dozens of points) when compared to elev liklihood (thousands of points)
self.adapttemp = self.temperature
def interpolateArray(self, coords=None, z=None, dz=None):
"""
Interpolate the irregular spaced dataset from badlands on a regular grid.
"""
x, y = np.hsplit(coords, 2)
dx = (x[1]-x[0])[0]
nx = int((x.max() - x.min())/dx+1)
ny = int((y.max() - y.min())/dx+1)
xi = np.linspace(x.min(), x.max(), nx)
yi = np.linspace(y.min(), y.max(), ny)
xi, yi = np.meshgrid(xi, yi)
xyi = np.dstack([xi.flatten(), yi.flatten()])[0]
XY = np.column_stack((x,y))
tree = cKDTree(XY)
distances, indices = tree.query(xyi, k=3)
if len(z[indices].shape) == 3:
z_vals = z[indices][:,:,0]
dz_vals = dz[indices][:,:,0]
else:
z_vals = z[indices]
dz_vals = dz[indices]
zi = np.average(z_vals,weights=(1./distances), axis=1)
dzi = np.average(dz_vals,weights=(1./distances), axis=1)
onIDs = np.where(distances[:,0] == 0)[0]
if len(onIDs) > 0:
zi[onIDs] = z[indices[onIDs,0]]
dzi[onIDs] = dz[indices[onIDs,0]]
zreg = np.reshape(zi,(ny,nx))
dzreg = np.reshape(dzi,(ny,nx))
return zreg,dzreg
def run_badlands(self, input_vector):
#Runs a badlands model with the specified inputs
#Create a badlands model instance
model = badlandsModel()
# Load the XmL input file
model.load_xml(str(self.run_nb), self.input, muted=True)
# Adjust erodibility based on given parameter
model.input.SPLero = input_vector[1]
model.flow.erodibility.fill(input_vector[1] )
# Adjust precipitation values based on given parameter
model.force.rainVal[:] = input_vector[0]
# Adjust m and n values
model.input.SPLm = input_vector[2]
model.input.SPLn = input_vector[3]
#Check if it is the etopo extended problem
if problem == 2: # will work for more parameters
model.input.CDm = input_vector[4] # submarine diffusion
model.input.CDa = input_vector[5] # aerial diffusion
#Check if it is the mountain problem
if problem==3:
#Round the input vector
k=round(input_vector[4],1) #to closest 0.1
#Load the current tectonic uplift parameters
tectonicValues=pandas.read_csv(str(model.input.tectFile[0]),sep=r'\s+',header=None,dtype=np.float).values
#Adjust the parameters by our value k, and save them out
newFile = "Examples/mountain/tect/uplift"+str(self.temperature)+"_"+str(k)+".csv"
newtect = pandas.DataFrame(tectonicValues*k)
newtect.to_csv(newFile,index=False,header=False)
#Update the model uplift tectonic values
model.input.tectFile[0]=newFile
elev_vec = collections.OrderedDict()
erodep_vec = collections.OrderedDict()
erodep_pts_vec = collections.OrderedDict()
for x in range(len(self.sim_interval)):
self.simtime = self.sim_interval[x]
model.run_to_time(self.simtime, muted=True)
elev, erodep = self.interpolateArray(model.FVmesh.node_coords[:, :2], model.elevation, model.cumdiff)
erodep_pts = np.zeros((self.erodep_coords.shape[0]))
for count, val in enumerate(self.erodep_coords):
erodep_pts[count] = erodep[val[0], val[1]]
elev_vec[self.simtime] = elev
erodep_vec[self.simtime] = erodep
erodep_pts_vec[self.simtime] = erodep_pts
return elev_vec, erodep_vec, erodep_pts_vec
def likelihood_func(self,input_vector ):
#print("Running likelihood function: ", input_vector)
pred_elev_vec, pred_erodep_vec, pred_erodep_pts_vec = self.run_badlands(input_vector )
tausq = np.sum(np.square(pred_elev_vec[self.simtime] - self.real_elev))/self.real_elev.size
tau_erodep = np.zeros(self.sim_interval.size)
#print(self.sim_interval.size, self.real_erodep_pts.shape)
for i in range( self.sim_interval.size):
tau_erodep[i] = np.sum(np.square(pred_erodep_pts_vec[self.sim_interval[i]] - self.real_erodep_pts[i]))/ self.real_erodep_pts.shape[1]
likelihood_elev = - 0.5 * np.log(2 * math.pi * tausq) - 0.5 * np.square(pred_elev_vec[self.simtime] - self.real_elev) / tausq
likelihood_erodep = 0
if self.check_likelihood_sed == True:
for i in range(1, self.sim_interval.size):
likelihood_erodep += np.sum(-0.5 * np.log(2 * math.pi * tau_erodep[i]) - 0.5 * np.square(pred_erodep_pts_vec[self.sim_interval[i]] - self.real_erodep_pts[i]) / tau_erodep[i]) # only considers point or core of erodep
likelihood = np.sum(likelihood_elev) + (likelihood_erodep * self.sedscalingfactor)
else:
likelihood = np.sum(likelihood_elev)
rmse_elev = np.sqrt(tausq)
rmse_erodep = np.sqrt(tau_erodep)
avg_rmse_er = np.average(rmse_erodep)
return [likelihood *(1.0/self.adapttemp), pred_elev_vec, pred_erodep_pts_vec, likelihood, rmse_elev, avg_rmse_er]
def run(self):
#This is a chain that is distributed to many cores. AKA a 'Replica' in Parallel Tempering
samples = self.samples
count_list = []
stepsize_vec = np.zeros(self.maxlimits_vec.size)
span = (self.maxlimits_vec-self.minlimits_vec)
for i in range(stepsize_vec.size): # calculate the step size of each of the parameters
stepsize_vec[i] = self.stepratio_vec[i] * span[i]
v_proposal = self.vec_parameters # initial param values passed to badlands
v_current = v_proposal # to give initial value of the chain
# initial predictions from Badlands model
print("Intital parameter predictions: ", v_current)
initial_predicted_elev, initial_predicted_erodep, init_pred_erodep_pts_vec = self.run_badlands(v_current)
#calc initial likelihood with initial parameters
[likelihood, predicted_elev, pred_erodep_pts, likl_without_temp, avg_rmse_el, avg_rmse_er] = self.likelihood_func(v_current )
print('\tinitial likelihood:', likelihood)
likeh_list = np.zeros((samples,2)) # one for posterior of likelihood and the other for all proposed likelihood
likeh_list[0,:] = [-10000, -10000] # to avoid prob in calc of 5th and 95th percentile later
count_list.append(0) # just to count number of accepted for each chain (replica)
accept_list = np.zeros(samples)
#---------------------------------------
#now, create memory to save all the accepted tau proposals
prev_accepted_elev = deepcopy(predicted_elev)
prev_acpt_erodep_pts = deepcopy(pred_erodep_pts)
sum_elev = deepcopy(predicted_elev)
sum_erodep_pts = deepcopy(pred_erodep_pts)
#print('time to change')
burnsamples = int(samples*self.burn_in)
#---------------------------------------
#now, create memory to save all the accepted proposals of rain, erod, etc etc, plus likelihood
pos_param = np.zeros((samples,v_current.size))
list_yslicepred = np.zeros((samples,self.real_elev.shape[0])) # slice mid y axis
list_xslicepred = np.zeros((samples,self.real_elev.shape[1])) # slice mid x axis
ymid = int(self.real_elev.shape[1]/2 )
xmid = int(self.real_elev.shape[0]/2)
list_erodep = np.zeros((samples,pred_erodep_pts[self.simtime].size))
list_erodep_time = np.zeros((samples , self.sim_interval.size , pred_erodep_pts[self.simtime].size))
start = time.time()
num_accepted = 0
num_div = 0
#pt_samples = samples * 0.5 # this means that PT in canonical form with adaptive temp will work till pt samples are reached. Set in arguments, default 0.5
init_count = 0
rmse_elev = np.zeros(samples)
rmse_erodep = np.zeros(samples)
#save
with file(('%s/experiment_setting.txt' % (self.filename)),'a') as outfile:
outfile.write('\nsamples_per_chain:,{0}'.format(self.samples))
outfile.write('\nburnin:,{0}'.format(self.burn_in))
outfile.write('\nnum params:,{0}'.format(self.num_param))
outfile.write('\ninitial_proposed_vec:,{0}'.format(v_proposal))
outfile.write('\nstepsize_vec:,{0}'.format(stepsize_vec))
outfile.write('\nstep_ratio_vec:,{0}'.format(self.stepratio_vec))
outfile.write('\nswap interval:,{0}'.format(self.swap_interval))
outfile.write('\nsim interval:,{0}'.format(self.sim_interval))
outfile.write('\nlikelihood_sed (T/F):,{0}'.format(self.check_likelihood_sed))
outfile.write('\nerodep_coords:,{0}'.format(self.erodep_coords))
outfile.write('\nsed scaling factor:,{0}'.format(self.sedscalingfactor))
self.event.clear()
for i in range(samples-1):
print ("Temperature: ", self.temperature, ' Sample: ', i ,"/",samples)
if i < pt_samples:
self.adapttemp = self.temperature #* ratio #
if i == pt_samples and init_count ==0: # move to MCMC canonical
self.adapttemp = 1
[likelihood, predicted_elev, pred_erodep_pts, likl_without_temp, avg_rmse_el, avg_rmse_er] = self.likelihood_func(v_proposal)
init_count = 1
# Update by perturbing all the parameters via "random-walk" sampler and check limits
v_proposal = np.random.normal(v_current,stepsize_vec)
for j in range(v_current.size):
if v_proposal[j] > self.maxlimits_vec[j]:
v_proposal[j] = v_current[j]
elif v_proposal[j] < self.minlimits_vec[j]:
v_proposal[j] = v_current[j]
#print(v_proposal)
# Passing paramters to calculate likelihood and rmse with new tau
[likelihood_proposal, predicted_elev, pred_erodep_pts, likl_without_temp, avg_rmse_el, avg_rmse_er] = self.likelihood_func(v_proposal)
final_predtopo= predicted_elev[self.simtime]
pred_erodep = pred_erodep_pts[self.simtime]
# Difference in likelihood from previous accepted proposal
diff_likelihood = likelihood_proposal - likelihood
try:
mh_prob = min(1, math.exp(diff_likelihood))
except OverflowError as e:
mh_prob = 1
u = random.uniform(0,1)
accept_list[i+1] = num_accepted
likeh_list[i+1,0] = likelihood_proposal
if u < mh_prob: # Accept sample
# Append sample number to accepted list
count_list.append(i)
likelihood = likelihood_proposal
v_current = v_proposal
pos_param[i+1,:] = v_current # features rain, erodibility and others (random walks is only done for this vector)
likeh_list[i + 1,1]=likelihood # contains all proposal liklihood (accepted and rejected ones)
list_yslicepred[i+1,:] = final_predtopo[:, ymid] # slice taken at mid of topography along y axis
list_xslicepred[i+1,:]= final_predtopo[xmid, :] # slice taken at mid of topography along x axis
list_erodep[i+1,:] = pred_erodep
rmse_elev[i+1,] = avg_rmse_el
rmse_erodep[i+1,] = avg_rmse_er
for x in range(self.sim_interval.size):
list_erodep_time[i+1,x, :] = pred_erodep_pts[self.sim_interval[x]]
num_accepted = num_accepted + 1
prev_accepted_elev.update(predicted_elev)
if i>burnsamples:
for k, v in prev_accepted_elev.items():
sum_elev[k] += v
for k, v in pred_erodep_pts.items():
sum_erodep_pts[k] += v
num_div += 1
else: # Reject sample
likeh_list[i + 1, 1]=likeh_list[i,1]
pos_param[i+1,:] = pos_param[i,:]
list_yslicepred[i+1,:] = list_yslicepred[i,:]
list_xslicepred[i+1,:]= list_xslicepred[i,:]
list_erodep[i+1,:] = list_erodep[i,:]
list_erodep_time[i+1,:, :] = list_erodep_time[i,:, :]
rmse_elev[i+1,] = rmse_elev[i,]
rmse_erodep[i+1,] = rmse_erodep[i,]
if i>burnsamples:
for k, v in prev_accepted_elev.items():
sum_elev[k] += v
for k, v in prev_acpt_erodep_pts.items():
sum_erodep_pts[k] += v
num_div += 1
if ( (i+1) % self.swap_interval == 0 ):
others = np.asarray([likelihood])
param = np.concatenate([v_current,others,np.asarray([self.temperature])])
# paramater placed in queue for swapping between chains
self.parameter_queue.put(param)
#signal main process to start and start waiting for signal for main
self.signal_main.set()
self.event.clear()
self.event.wait()
result = self.parameter_queue.get()
v_current= result[0:v_current.size]
#likelihood = result[v_current.size]
others = np.asarray([ likelihood])
param = np.concatenate([v_current,others,np.asarray([self.temperature])])
self.parameter_queue.put(param)
self.signal_main.set()
accepted_count = len(count_list)
accept_ratio = accepted_count / (samples * 1.0) * 100
print("param first:",param)
print("v_current",v_current)
print("others",others)
print("temp",np.asarray([self.temperature]))
#Save out the data for each chain
file_name = self.filename+'/posterior/pos_parameters/chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name,pos_param )
file_name = self.filename+'/posterior/predicted_topo/chain_xslice_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, list_xslicepred )
file_name = self.filename+'/posterior/predicted_topo/chain_yslice_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, list_yslicepred )
file_name = self.filename+'/posterior/pos_likelihood/chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name,likeh_list, fmt='%1.2f')
file_name = self.filename + '/posterior/accept_list/chain_' + str(self.temperature) + '_accept.txt'
np.savetxt(file_name, [accept_ratio], fmt='%1.2f')
file_name = self.filename + '/posterior/accept_list/chain_' + str(self.temperature) + '.txt'
np.savetxt(file_name, accept_list, fmt='%1.2f')
file_name = self.filename+'/posterior/rmse_elev_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, rmse_elev, fmt='%1.2f')
file_name = self.filename+'/posterior/rmse_erodep_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, rmse_erodep, fmt='%1.2f')
for s in range(self.sim_interval.size):
file_name = self.filename + '/posterior/predicted_erodep/chain_' + str(self.sim_interval[s]) + '_' + str(self.temperature) + '.txt'
np.savetxt(file_name, list_erodep_time[:,s, :] , fmt='%.2f')
for k, v in sum_elev.items():
sum_elev[k] = np.divide(sum_elev[k], num_div)
mean_pred_elevation = sum_elev[k]
sum_erodep_pts[k] = np.divide(sum_erodep_pts[k], num_div)
mean_pred_erodep_pnts = sum_erodep_pts[k]
file_name = self.filename + '/posterior/predicted_topo/chain_' + str(k) + '_' + str(self.temperature) + '.txt'
np.savetxt(file_name, mean_pred_elevation, fmt='%.2f')
class ParallelTempering:
def __init__(self, vec_parameters, num_chains, maxtemp,NumSample,swap_interval, fname, realvalues_vec, num_param, real_elev, erodep_pts, erodep_coords, simtime, siminterval, resolu_factor, run_nb, inputxml):
self.swap_interval = swap_interval
self.folder = fname
self.maxtemp = maxtemp
self.num_swap = 0
self.num_chains = num_chains
self.chains = []
self.temperatures = []
self.NumSamples = int(NumSample/self.num_chains)
self.sub_sample_size = max(1, int( 0.05* self.NumSamples))
self.show_fulluncertainity = False # needed in cases when you reall want to see full prediction of 5th and 95th percentile of topo. takes more space
self.real_erodep_pts = erodep_pts
self.real_elev = real_elev
self.resolu_factor = resolu_factor
self.num_param = num_param
self.erodep_coords = erodep_coords
self.simtime = simtime
self.sim_interval = siminterval
self.run_nb =run_nb
self.xmlinput = inputxml
self.vec_parameters = vec_parameters
self.realvalues = realvalues_vec
# create queues for transfer of parameters between process chain
#self.chain_parameters = [multiprocessing.Queue() for i in range(0, self.num_chains) ]
self.parameter_queue = [multiprocessing.Queue() for i in range(num_chains)]
self.chain_queue = multiprocessing.JoinableQueue()
self.wait_chain = [multiprocessing.Event() for i in range (self.num_chains)]
# two ways events are used to synchronize chains
self.event = [multiprocessing.Event() for i in range (self.num_chains)]
#self.wait_chain = [multiprocessing.Event() for i in range (self.num_chains)]
self.geometric = True
self.total_swap_proposals = 0
def default_beta_ladder(self, ndim, ntemps, Tmax): #https://github.com/konqr/ptemcee/blob/master/ptemcee/sampler.py
"""
Returns a ladder of :math:`\beta \equiv 1/T` under a geometric spacing that is determined by the
arguments ``ntemps`` and ``Tmax``. The temperature selection algorithm works as follows:
Ideally, ``Tmax`` should be specified such that the tempered posterior looks like the prior at
this temperature. If using adaptive parallel tempering, per `arXiv:1501.05823
<http://arxiv.org/abs/1501.05823>`_, choosing ``Tmax = inf`` is a safe bet, so long as
``ntemps`` is also specified.
"""
if type(ndim) != int or ndim < 1:
raise ValueError('Invalid number of dimensions specified.')
if ntemps is None and Tmax is None:
raise ValueError('Must specify one of ``ntemps`` and ``Tmax``.')
if Tmax is not None and Tmax <= 1:
raise ValueError('``Tmax`` must be greater than 1.')
if ntemps is not None and (type(ntemps) != int or ntemps < 1):
raise ValueError('Invalid number of temperatures specified.')
# geometrically spaced temperature ladder
# https://arxiv.org/pdf/1811.04343.pdf for more details on temperature ladder
maxtemp = Tmax
numchain = ntemps
b=[]
b.append(maxtemp)
last=maxtemp
for i in range(maxtemp):
last = last*(numchain**(-1/(numchain-1)))
b.append(last)
tstep = np.array(b)
if ndim > tstep.shape[0]:
# An approximation to the temperature step at large
# dimension
tstep = 1.0 + 2.0*np.sqrt(np.log(4.0))/np.sqrt(ndim)
else:
tstep = tstep[ndim-1]
appendInf = False
if Tmax == np.inf:
appendInf = True
Tmax = None
ntemps = ntemps - 1
if ntemps is not None:
if Tmax is None:
# Determine Tmax from ntemps.
Tmax = tstep ** (ntemps - 1)
else:
if Tmax is None:
raise ValueError('Must specify at least one of ``ntemps'' and '
'finite ``Tmax``.')
# Determine ntemps from Tmax.
ntemps = int(np.log(Tmax) / np.log(tstep) + 2)
betas = np.logspace(0, -np.log10(Tmax), ntemps)
if appendInf:
# Use a geometric spacing, but replace the top-most temperature with
# infinity.
betas = np.concatenate((betas, [0]))
return betas
def assign_temperatures(self):
# #Linear Spacing
# temp = 2
# for i in range(0,self.num_chains):
# self.temperatures.append(temp)
# temp += 2.5 #(self.maxtemp/self.num_chains)
# print (self.temperatures[i])
#Geometric Spacing
if self.geometric == True:
betas = self.default_beta_ladder(2, ntemps=self.num_chains, Tmax=self.maxtemp)
for i in range(0, self.num_chains):
self.temperatures.append(np.inf if betas[i] is 0 else 1.0/betas[i])
print (self.temperatures[i])
else:
tmpr_rate = (self.maxtemp /self.num_chains)
temp = 1
print("Temperatures...")
for i in xrange(0, self.num_chains):
self.temperatures.append(temp)
temp += tmpr_rate
print(self.temperatures[i])
def initialize_chains (self, minlimits_vec, maxlimits_vec, stepratio_vec, check_likelihood_sed, burn_in):
self.burn_in = burn_in
self.vec_parameters = np.random.uniform(minlimits_vec, maxlimits_vec) # will begin from diff position in each replica (comment if not needed)
self.assign_temperatures()
for i in xrange(0, self.num_chains):
self.chains.append(ptReplica( self.num_param, self.vec_parameters, minlimits_vec, maxlimits_vec, stepratio_vec, check_likelihood_sed ,self.swap_interval, self.sim_interval, self.simtime, self.NumSamples, self.real_elev, self.real_erodep_pts, self.erodep_coords, self.folder, self.xmlinput, self.run_nb,self.temperatures[i], self.parameter_queue[i],self.event[i], self.wait_chain[i],burn_in))
def swap_procedure(self, parameter_queue_1, parameter_queue_2):
# if parameter_queue_2.empty() is False and parameter_queue_1.empty() is False:
param1 = parameter_queue_1.get()
param2 = parameter_queue_2.get()
w1 = param1[0:self.num_param]
lhood1 = param1[self.num_param+1]
T1 = param1[self.num_param+1]
w2 = param2[0:self.num_param]
lhood2 = param2[self.num_param+1]
T2 = param2[self.num_param+1]
try:
swap_proposal = min(1,0.5*np.exp(min(709, lhood2 - lhood1)))
except OverflowError:
swap_proposal = 1
u = np.random.uniform(0,1)
swapped = False
if u < swap_proposal:
self.total_swap_proposals += 1
self.num_swap += 1
param_temp = param1
param1 = param2
param2 = param_temp
swapped = True
else:
swapped = False
self.total_swap_proposals += 1
return param1, param2,swapped
def run_chains (self ):
swap_proposal = np.ones(self.num_chains-1)
# create parameter holders for paramaters that will be swapped
replica_param = np.zeros((self.num_chains, self.num_param))
lhood = np.zeros(self.num_chains)
# Define the starting and ending of MCMC Chains
start = 0
end = self.NumSamples-1
number_exchange = np.zeros(self.num_chains)
filen = open(self.folder + '/num_exchange.txt', 'a')
#RUN MCMC CHAINS
for l in range(0,self.num_chains):
self.chains[l].start_chain = start
self.chains[l].end = end
for j in range(0,self.num_chains):
self.wait_chain[j].clear()
self.event[j].clear()
self.chains[j].start()
#SWAP PROCEDURE
swaps_appected_main =0
total_swaps_main =0
for i in range(int(self.NumSamples/self.swap_interval)):
count = 0
for index in range(self.num_chains):
if not self.chains[index].is_alive():
count+=1
self.wait_chain[index].set()
print(str(self.chains[index].temperature) +" Dead")
if count == self.num_chains:
break
print("Waiting")
timeout_count = 0
for index in range(0,self.num_chains):
print("Waiting for chain: {}".format(index+1))
flag = self.wait_chain[index].wait()
if flag:
print("Signal from chain: {}".format(index+1))
timeout_count += 1
if timeout_count != self.num_chains:
print("Skipping the swap!")
continue
print("Event occured")
for index in range(0,self.num_chains-1):
print('starting swap')
param_1, param_2, swapped = self.swap_procedure(self.parameter_queue[index],self.parameter_queue[index+1])
self.parameter_queue[index].put(param_1)
self.parameter_queue[index+1].put(param_2)
if index == 0:
if swapped:
swaps_appected_main += 1
total_swaps_main += 1
for index in range (self.num_chains):
self.event[index].set()
self.wait_chain[index].clear()
print("Joining processes")
#JOIN THEM TO MAIN PROCESS
for index in range(0,self.num_chains):
self.chains[index].join()
self.chain_queue.join()
print(number_exchange, 'num_exchange, process ended')
pos_param, likelihood_rep, accept_list, pred_topo, combined_erodep, accept, pred_topofinal, list_xslice, list_yslice, rmse_elev, rmse_erodep = self.show_results('chain_')
self.view_crosssection_uncertainity(list_xslice, list_yslice)
optimal_para, para_5thperc, para_95thperc = self.get_uncertainity(likelihood_rep, pos_param)
np.savetxt(self.folder+'/optimal_percentile_para.txt', [optimal_para, para_5thperc, para_95thperc] )
for s in range(self.num_param):
self.plot_figure(pos_param[s,:], 'pos_distri_'+str(s), self.realvalues[s] )
for i in range(self.sim_interval.size):
self.viewGrid(width=1000, height=1000, zmin=None, zmax=None, zData=pred_topo[i,:,:], title='Predicted Topography ', time_frame=self.sim_interval[i], filename= 'mean')
self.viewGrid(width=1000, height=1000, zmin=None, zmax=None, zData= self.real_elev , title='Ground truth Topography', time_frame= self.simtime, filename = 'ground_truth')
residual_elev = self.real_elev - pred_topo[self.sim_interval.size-1,:,:]
self.viewGrid(width=1000, height=1000, zmin=None, zmax=None, zData= residual_elev , title='Residual Topography', time_frame= self.simtime, filename = 'residual_elev')
#self.plot_figure(residual_elev.flatten(), 'residual_elev', [] )
if self.show_fulluncertainity == True: # this to be used when you need output of the topo predictions - 5th and 95th percentiles
pred_elev5th, pred_eroddep5th, pred_erd_pts5th = self.run_badlands(np.asarray(para_5thperc))
self.viewGrid(width=1000, height=1000, zmin=None, zmax=None, zData=pred_elev5th[self.simtime], title='Pred. Topo. - 5th Percentile', time_frame= self.simtime, filename= '5th')
pred_elev95th, pred_eroddep95th, pred_erd_pts95th = self.run_badlands(para_95thperc)
self.viewGrid(width=1000, height=1000, zmin=None, zmax=None, zData=pred_elev95th[self.simtime], title='Pred. Topo. - 95th Percentile', time_frame= self.simtime, filename = '95th')
pred_elevoptimal, pred_eroddepoptimal, pred_erd_optimal = self.run_badlands(optimal_para)
self.viewGrid(width=1000, height=1000, zmin=None, zmax=None, zData=pred_elevoptimal[self.simtime], title='Pred. Topo. - Optimal', time_frame= self.simtime, filename = 'optimal')
swap_perc = self.num_swap*100/self.total_swap_proposals
return (pos_param,likelihood_rep, accept_list, combined_erodep, pred_topofinal, swap_perc, accept, rmse_elev, rmse_erodep)
def view_crosssection_uncertainity(self, list_xslice, list_yslice):
print ('list_xslice', list_xslice.shape)
print ('list_yslice', list_yslice.shape)
ymid = int(self.real_elev.shape[1]/2 ) # cut the slice in the middle
xmid = int(self.real_elev.shape[0]/2)
print( 'ymid',ymid)
print( 'xmid', xmid)
print(self.real_elev)
print(self.real_elev.shape, ' shape')
x_ymid_real = self.real_elev[xmid, :]
y_xmid_real = self.real_elev[:, ymid ]
x_ymid_mean = list_xslice.mean(axis=1)
print( x_ymid_real.shape , ' x_ymid_real shape')
print( x_ymid_mean.shape , ' x_ymid_mean shape')
x_ymid_5th = np.percentile(list_xslice, 5, axis=1)
x_ymid_95th= np.percentile(list_xslice, 95, axis=1)
y_xmid_mean = list_yslice.mean(axis=1)
y_xmid_5th = np.percentile(list_yslice, 5, axis=1)
y_xmid_95th= np.percentile(list_yslice, 95, axis=1)
x = np.linspace(0, x_ymid_mean.size * self.resolu_factor, num=x_ymid_mean.size)
x_ = np.linspace(0, y_xmid_mean.size * self.resolu_factor, num=y_xmid_mean.size)
#ax.set_xlim(-width,len(ind)+width)
self.cross_section(x, x_ymid_mean, x_ymid_real, x_ymid_5th, x_ymid_95th, 'x_ymid_cross')
self.cross_section(x_, y_xmid_mean, y_xmid_real, y_xmid_5th, y_xmid_95th, 'y_xmid_cross')
def cross_section(self, x, pred, real, lower, higher, fname):
size = 15
plt.tick_params(labelsize=size)
params = {'legend.fontsize': size, 'legend.handlelength': 2}
plt.rcParams.update(params)
plt.plot(x, real, label='Ground Truth')
plt.plot(x, pred, label='Badlands Pred.')
plt.grid(alpha=0.75)
rmse_init = np.sqrt(np.sum(np.square(pred - real)) / real.size)
plt.fill_between(x, lower , higher, facecolor='g', alpha=0.2, label = 'Uncertainty')
#plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.legend(loc='best')
#plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3, fancybox=True, shadow=True)
plt.title("Topography cross section ", fontsize = size)
plt.xlabel(' Distance (km) ', fontsize = size)
plt.ylabel(' Height (m)', fontsize = size)
plt.tight_layout()
plt.savefig(self.folder+'/'+fname+'.pdf')
plt.clf()
return rmse_init
# Merge different MCMC chains y stacking them on top of each other
def show_results(self, filename):
burnin = int(self.NumSamples * self.burn_in)
pos_param = np.zeros((self.num_chains, self.NumSamples - burnin, self.num_param))
list_xslice = np.zeros((self.num_chains, self.NumSamples - burnin, self.real_elev.shape[1]))
list_yslice = np.zeros((self.num_chains, self.NumSamples - burnin, self.real_elev.shape[0]))
likehood_rep = np.zeros((self.num_chains, self.NumSamples - burnin, 2 )) # index 1 for likelihood posterior and index 0 for Likelihood proposals. Note all likilihood proposals plotted only
accept_percent = np.zeros((self.num_chains, 1))
accept_list = np.zeros((self.num_chains, self.NumSamples ))
topo = self.real_elev
replica_topo = np.zeros((self.sim_interval.size, self.num_chains, topo.shape[0], topo.shape[1])) #3D
combined_topo = np.zeros(( self.sim_interval.size, topo.shape[0], topo.shape[1]))
replica_erodep_pts = np.zeros(( self.num_chains, self.real_erodep_pts.shape[1] ))
combined_erodep = np.zeros((self.sim_interval.size, self.num_chains, self.NumSamples - burnin, self.real_erodep_pts.shape[1] ))
timespan_erodep = np.zeros((self.sim_interval.size, (self.NumSamples - burnin) * self.num_chains, self.real_erodep_pts.shape[1] ))
rmse_elev = np.zeros((self.num_chains, self.NumSamples-burnin))
rmse_erodep = np.zeros((self.num_chains, self.NumSamples-burnin))
for i in range(self.num_chains):
file_name = self.folder + '/posterior/pos_parameters/'+filename + str(self.temperatures[i]) + '.txt'
dat = np.loadtxt(file_name)
pos_param[i, :, :] = dat[burnin:,:]
file_name = self.folder + '/posterior/predicted_topo/chain_xslice_'+ str(self.temperatures[i]) + '.txt'
dat = np.loadtxt(file_name)
list_xslice[i, :, :] = dat[burnin:,:]
file_name = self.folder + '/posterior/predicted_topo/chain_yslice_'+ str(self.temperatures[i]) + '.txt'
dat = np.loadtxt(file_name)
list_yslice[i, :, :] = dat[burnin:,:]
file_name = self.folder + '/posterior/pos_likelihood/'+filename + str(self.temperatures[i]) + '.txt'
dat = np.loadtxt(file_name)
likehood_rep[i, :] = dat[burnin:]
file_name = self.folder + '/posterior/accept_list/' + filename + str(self.temperatures[i]) + '.txt'
dat = np.loadtxt(file_name)
accept_list[i, :] = dat
file_name = self.folder + '/posterior/accept_list/' + filename + str(self.temperatures[i]) + '_accept.txt'
dat = np.loadtxt(file_name)
accept_percent[i, :] = dat
file_name = self.folder+'/posterior/rmse_elev_chain_'+ str(self.temperatures[i])+ '.txt'
dat = np.loadtxt(file_name)
rmse_elev[i,:] = dat[burnin:]
file_name = self.folder+'/posterior/rmse_erodep_chain_'+ str(self.temperatures[i])+ '.txt'
dat = np.loadtxt(file_name)
rmse_erodep[i,:] = dat[burnin:]
for j in range(self.sim_interval.size):
file_name = self.folder+'/posterior/predicted_topo/chain_'+str(self.sim_interval[j])+'_'+ str(self.temperatures[i])+ '.txt'
dat_topo = np.loadtxt(file_name)
replica_topo[j,i,:,:] = dat_topo
file_name = self.folder+'/posterior/predicted_erodep/chain_'+str(self.sim_interval[j])+'_'+ str(self.temperatures[i])+ '.txt'
dat_erodep = np.loadtxt(file_name)
combined_erodep[j,i,:,:] = dat_erodep[burnin:,:]
posterior = pos_param.transpose(2,0,1).reshape(self.num_param,-1)
xslice = list_xslice.transpose(2,0,1).reshape(self.real_elev.shape[1],-1)
yslice = list_yslice.transpose(2,0,1).reshape(self.real_elev.shape[0],-1)
rmse_elev = rmse_elev.reshape(self.num_chains*(self.NumSamples - burnin),1)
rmse_erodep = rmse_erodep.reshape(self.num_chains*(self.NumSamples - burnin),1)
likelihood_vec = likehood_rep.transpose(2,0,1).reshape(2,-1)
for j in range(self.sim_interval.size):
for i in range(self.num_chains):
combined_topo[j,:,:] += replica_topo[j,i,:,:]
combined_topo[j,:,:] = combined_topo[j,:,:]/self.num_chains
dx = combined_erodep[j,:,:,:].transpose(2,0,1).reshape(self.real_erodep_pts.shape[1],-1)
timespan_erodep[j,:,:] = dx.T
accept = np.sum(accept_percent)/self.num_chains
pred_topofinal = combined_topo[-1,:,:] # get the last mean pedicted topo to calculate mean squared error loss
np.savetxt(self.folder + '/pos_param.txt', posterior.T)
np.savetxt(self.folder + '/likelihood.txt', likelihood_vec.T, fmt='%1.5f')
np.savetxt(self.folder + '/accept_list.txt', accept_list, fmt='%1.2f')
np.savetxt(self.folder + '/acceptpercent.txt', [accept], fmt='%1.2f')
return posterior, likelihood_vec.T, accept_list, combined_topo, timespan_erodep, accept, pred_topofinal, xslice, yslice, rmse_elev, rmse_erodep
def find_nearest(self, array,value): # just to find nearest value of a percentile (5th or 9th from pos likelihood)
idx = (np.abs(array-value)).argmin()
return array[idx], idx
def get_uncertainity(self, likehood_rep, pos_param ):
likelihood_pos = likehood_rep[:,1]
a = np.percentile(likelihood_pos, 5)
lhood_5thpercentile, index_5th = self.find_nearest(likelihood_pos,a)
b = np.percentile(likelihood_pos, 95)
lhood_95thpercentile, index_95th = self.find_nearest(likelihood_pos,b)
max_index = np.argmax(likelihood_pos) # find max of pos liklihood to get the max or optimal pos value
optimal_para = pos_param[:, max_index]
para_5thperc = pos_param[:, index_5th]
para_95thperc = pos_param[:, index_95th]
return optimal_para, para_5thperc, para_95thperc
# this is same method in Replica class - copied here to get error uncertainity in topo pred
def run_badlands(self, input_vector):
#Runs a badlands model with the specified inputs
#Create a badlands model instance
model = badlandsModel()
# Load the XmL input file
model.load_xml(str(self.run_nb), self.input, muted=True)
# Adjust erodibility based on given parameter
model.input.SPLero = input_vector[1]
model.flow.erodibility.fill(input_vector[1] )