-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathptBayeslands_gridtopo.py
1380 lines (1025 loc) · 59.2 KB
/
ptBayeslands_gridtopo.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
# mpl.use('Agg')
import os
import shutil
import sys
import random
import time
import operator
import math
import copy
import fnmatch
import collections
import numpy as np
import matplotlib as mpl
# import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab
import multiprocessing
import itertools
import plotly
import plotly.plotly as py
import pandas
import argparse
import pandas as pd
import seaborn as sns
import scipy.ndimage as ndimage
#plotly.offline.init_notebook_mode()
from plotly.graph_objs import *
from pylab import rcParams
from copy import deepcopy
from pylab import rcParams
from scipy import special
from PIL import Image
from io import StringIO
from cycler import cycler
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
from IPython.display import HTML
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from scipy.ndimage import filters
from scipy.ndimage import gaussian_filter
from problem_setup import problem_setup
#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 interval', dest="swap_interval",default= 2,type=int)
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('-rain_intervals','--rain_intervals', help='rain_intervals', dest="rain_intervals",default=4,type=int)
parser.add_argument('-epsilon','--epsilon', help='epsilon for inital topo', dest="epsilon",default=0.5,type=float)
parser.add_argument('-cov','--covariance', help='flag for covariance', dest="covariance",default=0,type=int)
args = parser.parse_args()
#parameters for Parallel Tempering
problem = args.problem
samples = args.samples
num_chains = args.num_chains
swap_interval = args.swap_interval
burn_in=args.burn_in
#maxtemp = int(num_chains * 5)/args.mt_val
maxtemp = args.mt_val
num_successive_topo = 4
pt_samples = args.pt_samples
epsilon = args.epsilon
rain_intervals = args.rain_intervals
covariance = args.covariance
method = 1 # type of formaltion for inittopo construction (Method 1 showed better results than Method 2)
class ptReplica(multiprocessing.Process):
def __init__(self, num_param, vec_parameters, sea_level, ocean_t, inittopo_expertknow, rain_region, rain_time, len_grid, wid_grid, minlimits_vec, maxlimits_vec, stepratio_vec, check_likelihood_sed , swap_interval, sim_interval, simtime, samples, init_elev, real_elev, real_erodep_pts, real_elev_pts, erodep_coords,elev_coords, filename, xmlinput, run_nb, tempr, parameter_queue,event , main_proc, burn_in, inittopo_estimated, covariance, Bayes_inittopoknowledge):
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.folder = 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.real_elev_pts = real_elev_pts
self.elev_coords = elev_coords
self.erodep_coords = erodep_coords
self.ocean_t = ocean_t
self.init_elev = init_elev
self.real_elev = real_elev
self.runninghisto = True
self.burn_in = burn_in
self.sim_interval = sim_interval
self.sedscalingfactor = 1 # 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
self.rain_region = rain_region
self.rain_time = rain_time
self.len_grid = len_grid
self.wid_grid = wid_grid# for initial topo grid size
self.inittopo_expertknow = inittopo_expertknow
self.inittopo_estimated = inittopo_estimated
self.adapt_cov = 50
self.cholesky = []
self.cov_init = False
self.use_cov = covariance
self.cov_counter = 0
self.repeated_proposal = False
self.sealevel_data = sea_level
self.Bayes_inittopoknowledge = Bayes_inittopoknowledge
def plot3d_plotly(self, zData, fname, replica_id):
zmin = zData.min()
zmax = zData.max()
tickvals= [0,50,75,-50]
height=1000
width=1000
title='Topography'
resolu_factor = 1
xx = (np.linspace(0, zData.shape[0]* resolu_factor, num=zData.shape[0]/10 ))
yy = (np.linspace(0, zData.shape[1] * resolu_factor, num=zData.shape[1]/10 ))
xx = np.around(xx, decimals=0)
yy = np.around(yy, decimals=0)
data = Data([Surface(x= zData.shape[0] , y= zData.shape[1] , z=zData, colorscale='YlGnBu')])
layout = Layout(title='Predicted Topography' , autosize=True, width=width, height=height,scene=Scene(
zaxis=ZAxis(title = ' Elev.(m) ', range=[zmin,zmax], autorange=False, nticks=6, gridcolor='rgb(255, 255, 255)',
gridwidth=2, zerolinecolor='rgb(255, 255, 255)', zerolinewidth=2),
xaxis=XAxis(title = ' x ', tickvals= xx, gridcolor='rgb(255, 255, 255)', gridwidth=2,
zerolinecolor='rgb(255, 255, 255)', zerolinewidth=2),
yaxis=YAxis(title = ' y ', tickvals= yy, gridcolor='rgb(255, 255, 255)', gridwidth=2,
zerolinecolor='rgb(255, 255, 255)', zerolinewidth=2),
bgcolor="rgb(244, 244, 248)"
)
)
fig = Figure(data=data, layout=layout)
graph = plotly.offline.plot(fig, auto_open=False, output_type='file', filename= self.folder + fname+ str(int(replica_id))+'.html', validate=False)
def process_inittopo(self, inittopo_vec):
length = self.real_elev.shape[0]
width = self.real_elev.shape[1]
len_grid = self.len_grid
wid_grid = self.wid_grid
#print('\n\nlength, width, len_grid, wid_grid ',length, width, len_grid, wid_grid)
sub_gridlen = 20 #int(length/len_grid) # 25
sub_gridwidth = 20 #int(width/wid_grid) # 25
new_length =len_grid * sub_gridlen
new_width =wid_grid * sub_gridwidth
'''if problem == 1:
reconstructed_topo = self.real_elev.copy() # to define the size
groundtruth_topo = self.real_elev.copy()
else:'''
reconstructed_topo = self.init_elev.copy() # to define the size
groundtruth_topo = self.init_elev.copy()
if problem == 1:
inittopo_vec = self.inittopo_expertknow.flatten() + inittopo_vec
else:
inittopo_vec = inittopo_vec
v_ = np.reshape(inittopo_vec, (sub_gridlen, -1) )#np.random.rand(len_grid,wid_grid)
for l in range(0,sub_gridlen-1):
for w in range(0,sub_gridwidth-1):
for m in range(l * len_grid,(l+1) * len_grid):
for n in range(w * wid_grid, (w+1) * wid_grid):
if(reconstructed_topo[m][n]> 300):
reconstructed_topo[m][n] = (reconstructed_topo[m][n]) + (v_[l][w])
width = reconstructed_topo.shape[0]
length = reconstructed_topo.shape[1]
for l in range(0,sub_gridlen -1 ):
w = sub_gridwidth-1
for m in range(l * len_grid,(l+1) * len_grid):
for n in range(w * wid_grid, length):
if(groundtruth_topo[m][n]> 300):
groundtruth_topo[m][n] = (groundtruth_topo[m][n]) + (v_[l][w])
for w in range(0,sub_gridwidth -1):
l = sub_gridlen-1
for m in range(l * len_grid,width):
for n in range(w * wid_grid, (w+1) * wid_grid):
if(groundtruth_topo[m][n]> 300):
groundtruth_topo[m][n] = (groundtruth_topo[m][n]) + (v_[l][w])
inside = reconstructed_topo[ 0 : sub_gridlen-2 * len_grid,0: (sub_gridwidth-2 * wid_grid) ]
for m in range(0 , inside.shape[0]):
for n in range(0 , inside.shape[1]):
if(groundtruth_topo[m][n]> 300):
groundtruth_topo[m][n] = inside[m][n]
groundtruth_topo = gaussian_filter(reconstructed_topo, sigma=(1 ,1 )) # change sigma to higher values if needed
self.plot3d_plotly(groundtruth_topo, '/recons_initialtopo/inittopo_smooth_', self.temperature *10)
#self.plot3d_plotly(reconstructed_topo, 'inittopo_')
return groundtruth_topo
def computeCovariance(self, i, pos_v):
cov_mat = np.cov(pos_v[:i,].T)
cov_noise_old = (self.stepratio_vec * self.stepratio_vec)*np.identity(cov_mat.shape[0], dtype = float)
cov_noise = self.stepsize_vec*np.identity(cov_mat.shape[0], dtype = float)
covariance = np.add(cov_mat, cov_noise)
L = np.linalg.cholesky(covariance)
self.cholesky = L
self.cov_init = True
# self.cov_counter += 1
def process_sealevel(self, coeff):
y = self.sealevel_data[:,1].copy()
timeframes = self.sealevel_data[:,0]
first = y[0:50] # sea leavel for 0 - 49 Ma to be untouched
second = y[50:] # this will be changed by sea level coeefecients proposed by MCMC
second_mat = np.reshape(second, (10, 10))
updated_mat = second_mat
print(coeff, ' coeff -----------------')
for l in range(0,second_mat.shape[0]):
for w in range(0,second_mat.shape[1]):
updated_mat[l][w] = (second_mat[l][w] * coeff[l]) + second_mat[l][w]
#print(updated_mat, ' updated ----------------------------- ')
reformed_sl = updated_mat.flatten()
combined_sl = np.concatenate([first, reformed_sl])
#print(proposed_sealevel, proposed_sealevel.shape, ' proposed_sealevel proposed_sealevel.shape ----------------------------- ')
#https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter
yhat = self.smooth(combined_sl, 10)
fig, ax = plt.subplots()
fnameplot = self.folder + '/recons_initialtopo/'+str(int(self.temperature*10))+'_sealevel_data.png'
ax.plot(timeframes, self.sealevel_data[:,1], 'k--', label='original')
ax.plot(timeframes, combined_sl, label='perturbed')
ax.plot(timeframes, yhat, label='smoothened')
ax.legend()
plt.savefig(fnameplot)
plt.clf()
proposed_sealevel = np.vstack([timeframes, yhat])
return proposed_sealevel
def smooth(self, y, box_pts):
#https://stackoverflow.com/questions/20618804/how-to-smooth-a-curve-in-the-right-way
#print(y.shape, y, ' ++ y ')
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='same')
return y_smooth
def run_badlands(self, input_vector):
#Runs a badlands model with the specified inputs
rain_regiontime = self.rain_region * self.rain_time # number of parameters for rain based on region and time
#Create a badlands model instance
model = badlandsModel()
#----------------------------------------------------------------
# Load the XmL input file
model.load_xml(str(self.run_nb), self.input, muted=True)
init = True
num_sealevel_coef = 10
if init == True:
geoparam = num_sealevel_coef + rain_regiontime+11 # note 10 parameter space is for erod, c-marine etc etc, some extra space ( taking out time dependent rainfall)
inittopo_vec = input_vector[geoparam:]
filename=self.input.split("/")
problem_folder=filename[0]+"/"+filename[1]+"/"
#Use the coordinates from the original dem file
#Update the initial topography
xi=int(np.shape(model.recGrid.rectX)[0]/model.recGrid.nx)
yi=int(np.shape(model.recGrid.rectY)[0]/model.recGrid.ny)
#And put the demfile on a grid we can manipulate easily
elev=np.reshape(model.recGrid.rectZ,(xi,yi))
inittopo_estimate = self.process_inittopo(inittopo_vec) #------------------------------------------
inittopo_estimate = inittopo_estimate[0: elev.shape[0], 0: elev.shape[1]] # bug fix but not good fix - temp @
#Put it back into 'Badlands' format and then re-load the model
filename=problem_folder+str(self.run_nb)+'/demfile_'+ str(int(self.temperature*10)) +'_demfile.csv'
elev_framex = np.vstack((model.recGrid.rectX,model.recGrid.rectY,inittopo_estimate.flatten()))
np.savetxt(filename, elev_framex.T, fmt='%1.2f' )
model.input.demfile=filename
model.build_mesh(model.input.demfile, verbose=False)
# Adjust precipitation values based on given parameter
#print(input_vector[0:rain_regiontime] )
model.force.rainVal = input_vector[0:rain_regiontime-1]
# Adjust erodibility based on given parameter
model.input.SPLero = input_vector[rain_regiontime]
model.flow.erodibility.fill(input_vector[rain_regiontime ] )
# Adjust m and n values
model.input.SPLm = input_vector[rain_regiontime+1]
model.input.SPLn = input_vector[rain_regiontime+2]
#Check if it is the etopo extended problem
#if problem == 4 or problem == 3: # will work for more parameters
model.input.CDm = input_vector[rain_regiontime+3] # submarine diffusion
model.input.CDa = input_vector[rain_regiontime+4] # aerial diffusion
if problem != 1:
model.slp_cr = input_vector[rain_regiontime+5]
model.perc_dep = input_vector[rain_regiontime+6]
model.input.criver = input_vector[rain_regiontime+7]
model.input.elasticH = input_vector[rain_regiontime+8]
model.input.diffnb = input_vector[rain_regiontime+9]
model.input.diffprop = input_vector[rain_regiontime+10]
sealevel_coeff = input_vector[rain_regiontime+10 : rain_regiontime+10+ num_sealevel_coef]
model.input.curve = self.process_sealevel(sealevel_coeff)
elev_vec = collections.OrderedDict()
erodep_vec = collections.OrderedDict()
erodep_pts_vec = collections.OrderedDict()
elev_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 = interpolateArray(model.FVmesh.node_coords[:, :2], model.elevation, model.cumdiff)
erodep_pts = np.zeros(self.erodep_coords.shape[0])
elev_pts = np.zeros(self.elev_coords.shape[0])
for count, val in enumerate(self.erodep_coords):
erodep_pts[count] = erodep[val[0], val[1]]
for count, val in enumerate(self.elev_coords):
elev_pts[count] = elev[val[0], val[1]]
print('Sim time: ', self.simtime , " Temperature: ", self.temperature)
elev_vec[self.simtime] = elev
erodep_vec[self.simtime] = erodep
erodep_pts_vec[self.simtime] = erodep_pts
elev_pts_vec[self.simtime] = elev_pts
return elev_vec, erodep_vec, erodep_pts_vec, elev_pts_vec
def likelihood_func(self,input_vector):
pred_elev_vec, pred_erodep_vec, pred_erodep_pts_vec, pred_elev_pts_vec = self.run_badlands(input_vector )
likelihood_elev_ocean = 0
rmse_ocean = np.zeros(self.sim_interval.size)
pred_topo_presentday = pred_elev_vec[self.simtime]
i = 6
pred_elev_vec_ = copy.deepcopy(pred_elev_vec) #pred_elev_vec.copy()
for i, time in enumerate(self.sim_interval):
p_elev_ocean = pred_elev_vec_[time]
r_elev_ocean = self.ocean_t[i,:,:]
# r_elev_ocean[r_elev_ocean<0] = 0
# r_elev_ocean[r_elev_ocean>0] = 1
p_elev_ocean[p_elev_ocean>0] = 0
p_elev_ocean[p_elev_ocean<0] = 1
matches = np.count_nonzero(p_elev_ocean==r_elev_ocean)
non_matches = p_elev_ocean.size -matches
print('\n time ', time, ' matches : ', matches ,' non matches : ', non_matches, 'percentage non match', (non_matches/p_elev_ocean.size)*100)
fig = plt.figure()
plt.imshow(p_elev_ocean, cmap='hot', interpolation='nearest')
plt.savefig(self.folder +'/pred_plots/'+ str(time) +'p_elev_ocean_original.png')
plt.close()
fig = plt.figure()
plt.imshow(r_elev_ocean, cmap='hot', interpolation='nearest')
plt.savefig(self.folder +'/pred_plots/' + str(time) +'r_elev_ocean.png')
plt.close()
tausq_ocean = np.sum(np.square(p_elev_ocean - r_elev_ocean))/self.real_elev.size
rmse_ocean[i] = tausq_ocean
likelihood_elev_ocean += np.sum(-0.5 * np.log(2 * math.pi * tausq_ocean) - 0.5 * np.square(p_elev_ocean - r_elev_ocean) / tausq_ocean )
i = i+ 1
tausq = np.sum(np.square(pred_elev_vec[self.simtime] - self.real_elev))/self.real_elev.size
likelihood_elev = np.sum(-0.5 * np.log(2 * math.pi * tausq ) - 0.5 * np.square(pred_elev_vec[self.simtime] - self.real_elev) / tausq )
if problem ==2:
tau_elev = np.sum(np.square(pred_elev_pts_vec[self.simtime] - self.real_elev_pts)) / self.real_elev_pts.shape[0]
tau_erodep = np.sum(np.square(pred_erodep_pts_vec[self.simtime] - self.real_erodep_pts))/ self.real_erodep_pts.shape[0]
likelihood_elev = np.sum(-0.5 * np.log(2 * math.pi * tau_elev ) - 0.5 * np.square(pred_elev_pts_vec[self.simtime] - self.real_elev_pts) / tau_elev )
likelihood_erodep = np.sum(-0.5 * np.log(2 * math.pi * tau_erodep ) - 0.5 * np.square(pred_erodep_pts_vec[self.sim_interval[len(self.sim_interval)-1]] - self.real_erodep_pts[0]) / tau_erodep ) # only considers point or core of erodep
else:
likelihood_erodep = 0
tau_elev = tausq
tau_erodep = 1
likelihood_ = (likelihood_elev/8) + (likelihood_erodep ) + (likelihood_elev_ocean/2)
#rmse_ocean = 0
rmse_elev = np.sqrt(tausq)
rmse_elev_ocean = np.average(rmse_ocean)
rmse_erodep = np.sqrt(tau_erodep)
rmse_elev_pts = np.sqrt(tau_elev)
likelihood = likelihood_*(1.0/self.adapttemp)
pred_topo_presentday = pred_elev_vec[self.simtime]
#self.plot3d_plotly(pred_topo_presentday, '/pred_plots/pred_badlands_', self.temperature *10) # Problem exists here XXXXXXX
print('LIKELIHOOD :--: Elev: ',likelihood_elev, '\tErdp: ', likelihood_erodep, '\tOcean:',likelihood_elev_ocean,'\tTotal: ', likelihood_, likelihood)
print('RMSE :--: Elev ', rmse_elev, 'Erdp', rmse_erodep, 'Ocean', rmse_elev_ocean)
return [likelihood, pred_elev_vec, pred_erodep_pts_vec, likelihood, rmse_elev_pts, rmse_erodep, rmse_ocean, rmse_elev_ocean ]
def run(self):
#This is a chain that is distributed to many cores. AKA a 'Replica' in Parallel Tempering
self.plot3d_plotly(self.real_elev, '/recons_initialtopo/real_evel', 1)
self.plot3d_plotly(self.init_elev, '/recons_initialtopo/expert_inittopo', 1)
if problem ==2:
fnameplot = self.folder + '/recons_initialtopo/'+'scatter_erodep_.png'
plt.scatter(self.erodep_coords[:,0], self.erodep_coords[:,1], s=2, c = 'b')
plt.scatter(self.elev_coords[:,0], self.elev_coords[:,1], s=2, c = 'r')
plt.savefig(fnameplot)
plt.clf()
fnameplot = self.folder + '/recons_initialtopo/'+'scatter_.png'
plt.scatter(self.elev_coords[:,0], self.elev_coords[:,1], s=2)
plt.savefig(fnameplot)
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
print(self.real_elev_pts.shape, ' self.real_elev_pts')
fnameplot = self.folder + '/recons_initialtopo/'+'scatter3d_elev_.png'
ax.scatter(self.elev_coords[:,0], self.elev_coords[:,1], self.real_elev_pts )
plt.savefig(fnameplot)
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
fnameplot = self.folder + '/recons_initialtopo/'+'scatter3d_erdp_.png'
ax.scatter(self.erodep_coords[:,0], self.erodep_coords[:,1], self.real_erodep_pts )
plt.savefig(fnameplot)
plt.clf()
x = np.arange(0, self.sealevel_data.shape[0], 1)
fig, ax = plt.subplots()
#print(x, ' xxx')
y = self.sealevel_data[:,1]
print(y, ' sea_level')
fnameplot = self.folder + '/recons_initialtopo/'+'sealevel_data.png'
ax.plot(x, y)
plt.savefig(fnameplot)
plt.clf()
#self.sealevel_data
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_predicted_elev, initial_predicted_erodep, init_pred_erodep_pts_vec, init_pred_elev_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, rmse_ocean, rmse_elev_ocean] = 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
rmse_elev = np.ones(samples)
rmse_erodep = np.ones(samples)
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))
init_count = 0
num_accepted = 0
num_div = 0
initial_samples = 5
pt_samplesratio = 0.35 # this means pt will be used in begiining and then mcmc with temp of 1 will take place
pt_samples = int(pt_samplesratio * samples)
with file(('%s/experiment_setting.txt' % (self.folder)),'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,elev_coords:,{0}'.format(self.erodep_coords))
outfile.write('\nsed scaling factor:,{0}'.format(self.sedscalingfactor))
start = time.time()
self.event.clear()
for i in range(samples-1):
print ("Temperature: ", self.temperature, ' Sample: ', i ,"/",samples, pt_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, rmse_ocean, rmse_elev_ocean] = self.likelihood_func(v_proposal)
init_count = 1
print(' * adapttemp --------------------------------------- 1 **** ***** ***')
if self.cov_init and self.use_cov==1:
v_p = np.random.normal(size = v_current.shape)
v_proposal = v_current + np.dot(self.cholesky,v_p)
# v_proposal = v_current + np.dot(self.cholesky,v_proposal)
else:
# Update by perturbing all the parameters via "random-walk" sampler and check limits
if i < initial_samples:
v_proposal = np.random.uniform(self.minlimits_vec, self.maxlimits_vec)
else:
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, rmse_ocean, rmse_elev_ocean] = 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:
# print ('diff_likelihood', diff_likelihood)
# print ('math.exp(diff_likelihood)', math.exp(diff_likelihood))
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
print("Temperature: ", self.temperature, 'Sample', i, 'Likelihood', likelihood , avg_rmse_el, 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 >= self.adapt_cov and i % self.adapt_cov == 0 and self.use_cov==1 ) :
print ('\ncov computed = i ',i, '\n')
self.computeCovariance(i,pos_param)
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]
save_res = np.array([i, num_accepted, likelihood, likelihood_proposal, rmse_elev[i+1,], rmse_erodep[i+1,]])
with file(('%s/posterior/pos_parameters/stream_chain_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([pos_param[i+1,:]]), fmt='%1.8f')
with file(('%s/posterior/predicted_topo/x_slice/stream_xslice_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([list_xslicepred[i+1,:]]), fmt='%1.2f')
with file(('%s/posterior/predicted_topo/y_slice/stream_yslice_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([list_yslicepred[i+1,:]]), fmt='%1.2f')
with file(('%s/posterior/stream_res_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([save_res]), fmt='%1.2f')
with file(('%s/performance/lhood/stream_res_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([likeh_list[i + 1,0]]), fmt='%1.2f')
with file(('%s/performance/accept/stream_res_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([accept_list[i+1]]), fmt='%1.2f')
with file(('%s/performance/rmse_erdp/stream_res_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([rmse_erodep[i+1,]]), fmt='%1.2f')
with file(('%s/performance/rmse_elev/stream_res_%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile,np.array([rmse_elev[i+1,]]), fmt='%1.2f')
with file(('%s/performance/rmse_ocean/stream_res_ocean%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile, np.array([rmse_elev_ocean]), fmt='%1.2f', newline='\n')
with file(('%s/performance/rmse_ocean/stream_res_ocean_t%s.txt' % (self.folder, self.temperature)),'a') as outfile:
np.savetxt(outfile, np.array([rmse_ocean]), fmt='%1.2f', newline='\n')
temp = list_erodep_time[i+1,-1,:]
temp = np.reshape(temp, temp.shape[0]*1)
file_name = self.folder + '/posterior/predicted_topo/sed/chain_' + str(self.temperature) + '.txt'
with file(file_name ,'a') as outfile:
np.savetxt(outfile, np.array([temp]), fmt='%1.2f')
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(accept_ratio, ' accept_ratio ')
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.folder + '/posterior/predicted_topo/topo/chain_' + str(k) + '_' + str(self.temperature) + '.txt'
np.savetxt(file_name, mean_pred_elevation, fmt='%.2f')
class ParallelTempering:
def __init__(self, vec_parameters, sea_level, ocean_t, inittopo_expertknow, rain_region, rain_time, len_grid, wid_grid, num_chains, maxtemp,NumSample,swap_interval, fname, realvalues_vec, num_param, init_elev, real_elev, erodep_pts, elev_pts, erodep_coords,elev_coords, simtime, siminterval, resolu_factor, run_nb, inputxml,inittopo_estimated, covariance, Bayes_inittopoknowledge):
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_pts = elev_pts
self.real_elev = real_elev
self.init_elev = init_elev
self.ocean_t = ocean_t
self.resolu_factor = resolu_factor
self.num_param = num_param
self.erodep_coords = erodep_coords
self.elev_coords = elev_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
self.sealevel_data = sea_level
# 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
self.rain_region = rain_region
self.rain_time = rain_time
self.len_grid = len_grid
self.wid_grid = wid_grid
self.inittopo_expertknow = inittopo_expertknow
self.inittopo_estimated = inittopo_estimated
self.Bayes_inittopoknowledge = Bayes_inittopoknowledge
self.covariance = covariance
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.')
tstep = np.array([25.2741, 7., 4.47502, 3.5236, 3.0232,
2.71225, 2.49879, 2.34226, 2.22198, 2.12628,
2.04807, 1.98276, 1.92728, 1.87946, 1.83774,
1.80096, 1.76826, 1.73895, 1.7125, 1.68849,
1.66657, 1.64647, 1.62795, 1.61083, 1.59494,
1.58014, 1.56632, 1.55338, 1.54123, 1.5298,
1.51901, 1.50881, 1.49916, 1.49, 1.4813,
1.47302, 1.46512, 1.45759, 1.45039, 1.4435,
1.4369, 1.43056, 1.42448, 1.41864, 1.41302,
1.40761, 1.40239, 1.39736, 1.3925, 1.38781,
1.38327, 1.37888, 1.37463, 1.37051, 1.36652,
1.36265, 1.35889, 1.35524, 1.3517, 1.34825,
1.3449, 1.34164, 1.33847, 1.33538, 1.33236,
1.32943, 1.32656, 1.32377, 1.32104, 1.31838,
1.31578, 1.31325, 1.31076, 1.30834, 1.30596,
1.30364, 1.30137, 1.29915, 1.29697, 1.29484,
1.29275, 1.29071, 1.2887, 1.28673, 1.2848,
1.28291, 1.28106, 1.27923, 1.27745, 1.27569,
1.27397, 1.27227, 1.27061, 1.26898, 1.26737,
1.26579, 1.26424, 1.26271, 1.26121,
1.25973])
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):
#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.assign_temperatures()
for i in xrange(0, self.num_chains):
self.vec_parameters = np.random.uniform(minlimits_vec, maxlimits_vec)
self.chains.append(ptReplica( self.num_param, self.vec_parameters, self.sealevel_data, self.ocean_t, self.inittopo_expertknow, self.rain_region, self.rain_time, self.len_grid, self.wid_grid, minlimits_vec, maxlimits_vec, stepratio_vec, check_likelihood_sed ,self.swap_interval, self.sim_interval, self.simtime, self.NumSamples, self.init_elev, self.real_elev, self.real_erodep_pts, self.real_elev_pts, self.erodep_coords,self.elev_coords, self.folder, self.xmlinput, self.run_nb,self.temperatures[i], self.parameter_queue[i],self.event[i], self.wait_chain[i],burn_in, self.inittopo_estimated, self.covariance, self.Bayes_inittopoknowledge))
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]