-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpt_multicore.py
1897 lines (1253 loc) · 68.6 KB
/
pt_multicore.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, Ratneel Deo and Jodie Pall Email: c.rohitash@gmail.com
#rohitash-chandra.github.io
# : Parallel tempering for multi-core systems - PT-BayesReef
#related: https://github.com/pyReef-model/pt-BayesReef
from __future__ import print_function, division
import multiprocessing
import gc
import os
import math
import time
import random
import csv
import numpy as np
from numpy import inf
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib import ticker
from matplotlib.cm import terrain, plasma, Set2
from pylab import rcParams
from pyReefCore.model import Model
from pyReefCore import plotResults
from cycler import cycler
from scipy import stats
import sys
from sys import getsizeof
config = 2 # for parameter limits config
cmap=plt.cm.Set2
c = cycler('color', cmap(np.linspace(0,1,8)) )
plt.rcParams["axes.prop_cycle"] = c
class ptReplica(multiprocessing.Process):
def __init__(self, samples,filename,xmlinput,vis,num_communities, vec_parameters, realvalues, maxlimits_vec,minlimits_vec,stepratio_vec,
swap_interval,simtime, core_depths, core_data, tempr, parameter_queue,event , main_proc, burn_in, pt_stage):
#self.chains.append(ptReplica(self.NumSamples,self.folder,self.xmlinput, self.vis, self.communities, vec_parameters, self.realvalues, self.maxlimits_vec, self.minlimits_vec, self.stepratio_vec, self.swap_interval, self.simtime, self.core_depths, self.core_data,
#self.temperature[i], self.chain_parameters[i], self.event[i], self.wait_chain[i], self.burn_in))
#--------------------------------------------------------
multiprocessing.Process.__init__(self)
self.samples = samples
self.filename = filename
self.input = xmlinput
self.vis = vis
self.communities = num_communities
self.vec_parameters = vec_parameters
self.swap_interval = swap_interval
self.simtime = simtime
self.realvalues_vec = realvalues # true values of free parameters for comparision. Note this will not be avialable in real world application
self.num_param = vec_parameters.size
self.temperature = tempr
self.adapttemp = tempr
self.processID = tempr
self.parameter_queue = parameter_queue
self.event = event
self.signal_main = main_proc
# self.run_nb = run_nb
self.burn_in = burn_in
self.sedsim = True
self.flowsim = True
self.d_sedprop = float(np.count_nonzero(core_data[:,self.communities]))/core_data.shape[0]
self.initial_sed = []
self.initial_flow = []
self.font = 10
self.width = 1
self.core_depths = core_depths
self.core_data = core_data
self.runninghisto = False # if you want to have histograms of the chains during runtime in pos_variables folder NB: this has issues in Artimis
self.maxlimits_vec = maxlimits_vec
self.minlimits_vec = minlimits_vec
self.stepratio_vec = stepratio_vec
self.sedlimits = [0, self.maxlimits_vec[2] ]
self.flowlimits = [0, self.maxlimits_vec[3] ]
self.pt_stage = pt_stage
def run_Model_(self, input_vector):
reef = Model()
reef.convert_vector(self.communities, input_vector, self.sedsim, self.flowsim) #model.py
self.true_sed, self.true_flow = reef.load_xml(self.input, self.sedsim, self.flowsim)
# if self.vis[0] == True:
# reef.core.initialSetting(size=(8,2.5), size2=(8,3.5)) # View initial parameters
reef.run_to_time(self.simtime,showtime=100.)
# if self.vis[1] == True:
# reef.plot.drawCore(lwidth = 3, colsed=self.colors, coltime = self.colors2, size=(9,8), font=8, dpi=300)
sim_output_t, sim_timelay = reef.plot.convertTimeStructure() #modelPlot.py
sim_output_d = reef.plot.convertDepthStructure(self.communities, self.core_depths) #modelPlot.py
# predicted_core = reef.convert_core(self.communities, output_core, self.core_depths) #model.py
# return predicted_core
#return sim_output_t, sim_output_d,sim_timelay
return sim_output_d
def run_Model(self, x ):
reef = Model()
print(x, ' * input_vector * ')
input_vector = np.asarray(x)
#reef.convert_vector(self.communities, input_vector, self.sedsim, self.flowsim) #model.py
new_shape = self.communities*4
opt_Sed = input_vector[0:new_shape].reshape(4,self.communities)
#print(opt_Sed, ' opt_sed ** --------------', self.adapttemp)
opt_Flow = input_vector[new_shape:(new_shape*2)].reshape(4,self.communities)
#print(opt_Flow, ' opt_sed ** --------------', self.adapttemp)
reef.opt_Sed = opt_Sed.T
reef.opt_Flow = opt_Flow.T
x = input_vector[new_shape*2]
y = input_vector[(new_shape*2)+1]
diagmat = np.zeros((self.communities, self.communities))
np.fill_diagonal(diagmat, x)
for i in range(0, self.communities - 1):
diagmat[i][i + 1] = y
diagmat[i + 1][i] = y
reef.opt_cMatrix = diagmat
tempParam= float(input_vector[(new_shape*2)+2])
reef.opt_malthusParam = np.full(self.communities, tempParam)
self.initial_sed, self.initial_flow = reef.load_xml(self.input, self.sedsim, self.flowsim)
#print(self.initial_sed, self.initial_flow , ' * initial sed and initial flow')
if self.vis[0] == True:
reef.core.initialSetting(size=(8,2.5), size2=(8,3.5)) # View initial parameters
reef.run_to_time(self.simtime,showtime=100.)
if self.vis[1] == True:
from matplotlib.cm import terrain, plasma
nbcolors = len(reef.core.coralH)+10
colors = terrain(np.linspace(0, 1.8, nbcolors))
nbcolors = len(reef.core.layTime)+3
colors2 = plasma(np.linspace(0, 1, nbcolors))
#reef.plot.drawCore(lwidth = 3, colsed=colors, coltime = colors2, size=(9,8), font=8, dpi=300)
output_core = reef.plot.core_timetodepth(self.communities, self.core_depths) #modelPlot.py
#predicted_core = reef.convert_core(self.communities, output_core, self.core_depths) #model.py
#return predicted_core
return output_core
def convert_core_format(self, core, communities):
vec = np.zeros(core.shape[0])
for n in range(len(vec)):
idx = np.argmax(core[n,:])# get index,
vec[n] = idx+1 # +1 so that zero is preserved as 'none'
return vec
def give_weight(self, arr):
index_array = np.zeros(arr.shape[0])
for i in range(0, arr.shape[0]):
if (arr[i] == 0):
index_array[i] = 1
else:
index_array[i] = 0
return index_array
def convertmat_assemindex(self, arr):
index_array = np.zeros(arr.shape[0])
for i in range(0, arr.shape[0]):
for j in range(0, arr.shape[1]):
if (arr[i][j] == 1):
index_array[i] = j
return index_array
def score_updated(self, predictions, targets):
# where there is 1 in the sed column, count
predictions = np.where(predictions > 0.5, 1, 0)
p = self.convertmat_assemindex(predictions) #predictions.dot(1 << np.arange(predictions.shape[-1]))
a = self.convertmat_assemindex(self.core_data)
diff = np.absolute( p-a)
weight_array = self.give_weight(diff)
score = np.sum(weight_array)/weight_array.shape[0]
return (1- score) * 100 #+ sedprop
def likelihood_func(self, core_data, input_v):
ax = -0.10
ay = -0.10
mal = 0.01
#-1493.2790256300846
'''sed1=[0.0009, 0.0015, 0.0023] # true values for synthetic 3 asssemblege problem (flow and sed)
sed2=[0.0015, 0.0017, 0.0024]
sed3=[0.0016, 0.0028, 0.0027]
sed4=[0.0017, 0.0031, 0.0043]
flow1=[0.055, 0.008 ,0.]
flow2=[0.082, 0.051, 0.]
flow3=[0.259, 0.172, 0.058]
flow4=[0.288, 0.185, 0.066] '''
#v_proposal = np.concatenate((sed1,sed2,sed3,sed4,flow1,flow2,flow3,flow4))
#input_v = np.append(v_proposal,(ax,ay,mal))
#input_v[0: 12] = v_proposal[0:12] #does not work
#input_v[12: 24] = v_proposal[12:24] #works
#print(input_v.shape, input_v, ' ++++++++++++++ ')
#v = np.ravel(input_v)
#input_v[0: 24] = np.asarray(xxx_)
input_vector = input_v.tolist()
pred_core = self.run_Model( input_vector )
pred_core = pred_core.T
intervals = pred_core.shape[0]
print(pred_core[0:10,:])
z = np.zeros((intervals,self.communities+1))
#print(z, intervals, ' is z int')
for n in range(intervals):
idx_data = np.argmax(core_data[n,:])
idx_model = np.argmax(pred_core[n,:])
if ((pred_core[n,self.communities] != 1.) and (idx_data == idx_model)): #where sediment !=1 and max proportions are equal:
z[n,idx_data] = 1
#diff = self.diffScore(sim_prop_d,gt_prop_d, intervals)
diff_ = self.score_updated(pred_core, core_data)
z = z + 0.1
z = z/(1+(1+self.communities)*0.1)
loss = np.log(z)
sum_loss = np.sum(loss)
print(input_v, ' input_v * ', sum_loss, diff_)
# *(1.0/self.adapttemp),
return [sum_loss, pred_core, diff_]
def save_core(self,reef,naccept):
path = '%s/%s' % (self.filename, naccept)
if not os.path.exists(path):
os.makedirs(path)
# Initial settings #
reef.core.initialSetting(size=(8,2.5), size2=(8,4.5), dpi=300, fname='%s/a_thres_%s_' % (path, naccept))
# Community population evolution #
reef.plot.speciesDepth(colors=self.colors, size=(8,4), font=8, dpi=300, fname =('%s/b_popd_%s.png' % (path,naccept)))
reef.plot.speciesTime(colors=self.colors, size=(8,4), font=8, dpi=300,fname=('%s/c_popt_%s.png' % (path,naccept)))
reef.plot.accomodationTime(size=(8,4), font=8, dpi=300, fname =('%s/d_acct_%s.pdf' % (path,naccept)))
# Draw core #
reef.plot.drawCore(lwidth = 3, colsed=self.colors, coltime = self.colors2, size=(9,8), font=8, dpi=300,
figname=('%s/e_core_%s' % (path, naccept)), filename=('%s/core_%s.csv' % (path, naccept)), sep='\t')
return
def proposal_vec(self, v_current):
size_sed = 4 * self.communities
size_flow = 4 * self.communities
max_a = self.maxlimits_vec[1]
max_m = self.maxlimits_vec[0]
step_sed = self.stepratio_vec[2]
step_flow= self.stepratio_vec[3]
#if self.sedsim == True:
tmat = v_current[0:size_sed]#np.concatenate((sed1,sed2,sed3,sed4)).reshape(4,self.communities)
tmat = tmat.reshape(4,self.communities)
tmatrix = tmat.T
t2matrix = np.zeros((tmatrix.shape[0], tmatrix.shape[1]))
for x in range(self.communities):#-3):
for s in range(tmatrix.shape[1]):
t2matrix[x,s] = tmatrix[x,s] + np.random.normal(0,step_sed)
if t2matrix[x,s] > self.sedlimits[1]:
t2matrix[x,s] = tmatrix[x,s]
elif t2matrix[x,s] < self.sedlimits[0]:
t2matrix[x,s] = tmatrix[x,s]
'''if t2matrix[x,s] >= self.sedlimits[x,1]:
t2matrix[x,s] = tmatrix[x,s]
elif t2matrix[x,s] <= self.sedlimits[x,0]:
t2matrix[x,s] = tmatrix[x,s]'''
# reorder each row , then transpose back as sed1, etc.
tmp = np.zeros((self.communities,4))
for x in range(t2matrix.shape[0]):
a = np.sort(t2matrix[x,:])
tmp[x,:] = a
tmat = tmp.T
p_sed1 = tmat[0,:]
p_sed2 = tmat[1,:]
p_sed3 = tmat[2,:]
p_sed4 = tmat[3,:]
#if self.flowsim == True:
tmat = v_current[size_sed:size_sed+size_flow] #np.concatenate((flow1,flow2,flow3,flow4)).reshape(4,self.communities)
tmat = tmat.reshape(4,self.communities)
tmatrix = tmat.T
t2matrix = np.zeros((tmatrix.shape[0], tmatrix.shape[1]))
for x in range(self.communities):#-3):
for s in range(tmatrix.shape[1]):
t2matrix[x,s] = tmatrix[x,s] + np.random.normal(0,step_flow)
if t2matrix[x,s] > self.flowlimits[1]:
t2matrix[x,s] = tmatrix[x,s]
elif t2matrix[x,s] < self.flowlimits[0]:
t2matrix[x,s] = tmatrix[x,s]
# reorder each row , then transpose back as flow1, etc.
tmp = np.zeros((self.communities,4))
for x in range(t2matrix.shape[0]):
a = np.sort(t2matrix[x,:])
tmp[x,:] = a
tmat = tmp.T
p_flow1 = tmat[0,:]
p_flow2 = tmat[1,:]
p_flow3 = tmat[2,:]
p_flow4 = tmat[3,:]
cm_ax = v_current[size_sed+size_flow]
cm_ay = v_current[size_sed+size_flow+1]
m = v_current[size_sed+size_flow+2]
#stepsize_ratio = [step_m, step_a, step_sed, step_flow]
#max_limits = [max_m, max_a, sedlim[1], flowlim[1]]
#min_limits = [0, 0, sedlim[0], flowlim[0] ]
step_a = self.stepratio_vec[1]
step_m = self.stepratio_vec[0]
p_ax = cm_ax + np.random.normal(0,step_a,1)
if p_ax > 0:
p_ax = cm_ax
elif p_ax < max_a:
p_ax = cm_ax
p_ay = cm_ay + np.random.normal(0,step_a,1)
if p_ay > 0:
p_ay = cm_ay
elif p_ay < max_a:
p_ay = cm_ay
p_m = m + np.random.normal(0,step_m,1)
if p_m < 0:
p_m = m
elif p_m > max_m:
p_m = m
glv_pro = np.array([p_ax,p_ay,p_m])
v_proposal = np.concatenate((p_sed1,p_sed2,p_sed3,p_sed4,p_flow1,p_flow2,p_flow3,p_flow4))
for a in glv_pro:
v_proposal = np.append(v_proposal, a)
return v_proposal #np.ravel(v_proposal)
def run(self):
# Note this is a chain that is distributed to many cores. The chain is also known as Replica in Parallel Tempering
data_size = self.core_data.shape[0]
x_data = self.core_depths
y_data = self.core_data
data_vec = self.convert_core_format(self.core_data, self.communities)
samples = self.samples
burnin = int(self.burn_in * samples)
#pt_stage = int(0.99 * samples) # paralel tempering is used only for exploration, it does not form the posterior, later mcmc in parallel is used with swaps
pt_samples = int(self.pt_stage * samples) # paralel tempering is used only for exploration, it does not form the posterior, later mcmc in parallel is used with swaps
#pt_samples = (self.samples * 0.9)
communities = self.communities
num_param = self.num_param
burnsamples = int(samples*self.burn_in)
count_list = []
# initial values of the parameters to be passed to Blackbox model
v_proposal = self.vec_parameters
v_current = v_proposal # to give initial value of the chain
# Create memory to save all the accepted proposals of parameters, model predictions and likelihood
pos_param = np.empty((samples,v_current.size))
pos_param[0,:] = v_proposal # assign first proposal
#----------------------------------------------------------------------------
for i in range(1):
likelihood, rep_predcore_, rep_diffscore = self.likelihood_func( self.core_data, v_proposal.copy())
predcore = self.convert_core_format(rep_predcore_, self.communities)
pos_samples_d = np.empty((samples, self.core_depths.size)) # list of all accepted (plus repeats) of pred cores
pos_samples_d[0,:] = predcore # assign the first core pred
pos_likl = np.empty((samples, 2)) # one for posterior of likelihood and the other for all proposed likelihood
pos_likl[0,:] = [-10000, -10000] # to avoid prob in calc of 5th and 95th percentile later
list_diffscore = np.empty(samples)
print (i, '\tInitial likelihood:', likelihood, 'and diff:', rep_diffscore)
#---------------------------------------
print ( '\t done: ----------------------------------+++++++++++++++++++++++++++--')
count_list.append(0) # To count number of accepted for each chain (replica)
accept_list = np.empty(samples)
start = time.time()
num_accepted = 0
with file(('%s/description.txt' % (self.filename)),'a') as outfile:
outfile.write('\nChain Temp: {0}'.format(self.temperature))
outfile.write('\n\tSamples: {0}'.format(self.samples))
outfile.write('\n\tInitial proposed vector\n\t{0}'.format(v_proposal))
#---------------------------------------
print('Begin sampling using MCMC random walk')
#b = 0
init_count = 0
for i in range(samples-1):
if i < pt_samples:
self.adapttemp = 1 #self.temperature #* ratio #
if i == pt_samples and init_count ==0: # move to MCMC canonical
self.adapttemp = 1
likelihood_proposal, rep_predcore_, rep_diffscore = self.likelihood_func( self.core_data, v_proposal.copy())
init_count = 1
#print(v_current, ' v_current')
v_proposal = self.proposal_vec(v_current)
likelihood_proposal, rep_predcore_, rep_diffscore = self.likelihood_func( self.core_data, v_proposal.copy())
predcore = self.convert_core_format(rep_predcore_, self.communities)
diff_likelihood = likelihood_proposal - likelihood
print(likelihood_proposal, diff_likelihood, ' + -------------------- + ')
try:
mh_prob = min(1, math.exp(diff_likelihood))
except OverflowError as e:
mh_prob = 1
u = random.uniform(0,1)
#print('u:', u, 'MH probability:', mh_prob)
#print((i % self.swap_interval), i, self.swap_interval, 'mod swap')
pos_likl[i+1,0] = likelihood_proposal
list_diffscore[i +1] = rep_diffscore
accept_list[i+1] = num_accepted
if u < mh_prob: # Accept sample
#b = b+1
print ('Accepted Sample',i, ' \n\tLikelihood ', likelihood_proposal,'\n\tTemperature:', self.temperature,'\n\t accepted, sample, diff ----------------->:', num_accepted, rep_diffscore)
count_list.append(i) # Append sample number to accepted list
num_accepted = num_accepted + 1
v_current = v_proposal
#print(v_proposal)
likelihood = likelihood_proposal
pos_likl[i + 1,1]=likelihood # contains all proposal liklihood (accepted and rejected ones)
pos_param[i+1,:] = v_current # features rain, erodibility and others (random walks is only done for this vector)
pos_samples_d[i+1,:] = predcore
else: # Reject sample
#b = i
pos_likl[i + 1, 1] = pos_likl[i,1]
pos_param[i+1,:] = pos_param[i,:]
pos_samples_d[i+1,:] = pos_samples_d[i,:]
#----------------------------------------------------------------------------------------
if ( i % self.swap_interval == 0 ):
others = np.asarray([likelihood])
param = np.concatenate([v_current,others])
# 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.wait()
# retrieve parametsrs fom ques if it has been swapped
if not self.parameter_queue.empty() :
try:
result = self.parameter_queue.get()
v_current= result[0:v_current.size]
likelihood = result[v_current.size]
del result
except:
print ('error')
accepted_count = len(count_list)
accept_ratio = accepted_count / (samples * 1.0) * 100
#---------------------------------------------------------------
others = np.asarray([ likelihood])
param = np.concatenate([v_current,others])
self.parameter_queue.put(param)
file_name = self.filename+'/posterior/pos_likelihood/chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name,pos_likl, 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/pos_parameters/chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name,pos_param )
file_name = self.filename+'/posterior/accept_list/diffscorechain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, list_diffscore)
file_name = self.filename+'/posterior/predicted_core/pos_samples_d/chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, pos_samples_d, fmt='%1.2f')
self.signal_main.set()
return
class ParallelTempering:
def __init__(self, problem, num_chains,communities, NumSample,fname,xmlinput,num_param,maxtemp,swap_interval,simtime,true_vec_parameters, core_depths, core_data, vis, maxlimits_vec, minlimits_vec , stepratio_vec, burn_in, pt_stage):
self.num_chains = num_chains
self.communities = communities
self.NumSamples = int(NumSample/self.num_chains)
self.folder = fname
self.xmlinput = xmlinput
self.num_param = num_param
self.maxtemp = maxtemp
self.swap_interval = swap_interval
self.simtime = simtime
self.realvalues = true_vec_parameters
self.core_depths = core_depths
self.core_data = core_data
self.chains = []
self.temperature = []
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. Takes more space
# Create queues for transfer of parameters between process chain
self.chain_parameters = [multiprocessing.Queue() for i in range(0, self.num_chains) ]
self.geometric = True
# Two ways events are used to synchronise 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.vis = vis
self.communities = communities
self.maxlimits_vec = maxlimits_vec
self.minlimits_vec = minlimits_vec
self.stepratio_vec = stepratio_vec
self.burn_in = burn_in
self.pt_stage = pt_stage
self.problem = problem
self.initial_sed = []
self.initial_flow = []
# Assign temperature dynamically
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):
# #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.temperature.append(np.inf if betas[i] is 0 else 1.0/betas[i])
print (self.temperature[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.temperature[i])
'''def assign_temptarures(self):
tmpr_rate = (self.maxtemp /self.num_chains)
temp = 1
for i in xrange(0, self.num_chains):
self.temperature.append(temp)
temp += tmpr_rate
print('self.temperature[%s]' % i,self.temperature[i])'''
def initialise_chains (self):
self.assign_temperatures()
for i in xrange(0, self.num_chains):
vec_parameters = self.initial_replicaproposal()
print(vec_parameters, ' vec init ', i)
self.chains.append(ptReplica(self.NumSamples,self.folder,self.xmlinput, self.vis, self.communities, vec_parameters, self.realvalues, self.maxlimits_vec, self.minlimits_vec, self.stepratio_vec, self.swap_interval, self.simtime, self.core_depths, self.core_data,
self.temperature[i], self.chain_parameters[i], self.event[i], self.wait_chain[i], self.burn_in, self.pt_stage))
def run_chains (self):
# only adjacent chains can be swapped therefore, the number of proposals is ONE less num_chains
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 the MCMC chains
#-------------------------------------------------------------------------------------
for l in range(0,self.num_chains):
self.chains[l].start_chain = start
self.chains[l].end = end
#-------------------------------------------------------------------------------------
# run the MCMC chains
#-------------------------------------------------------------------------------------
for j in range(0,self.num_chains):
self.chains[j].start()
flag_running = True
while flag_running:
#-------------------------------------------------------------------------------------
# wait for chains to complete one pass through the samples
#-------------------------------------------------------------------------------------
for j in range(0,self.num_chains):
#print (j, ' - waiting')
self.wait_chain[j].wait()
#-------------------------------------------------------------------------------------
#get info from chains
#-------------------------------------------------------------------------------------
for j in range(0,self.num_chains):
if self.chain_parameters[j].empty() is False :
result = self.chain_parameters[j].get()
replica_param[j,:] = result[0:self.num_param]
lhood[j] = result[self.num_param]
del result
# create swapping proposals between adjacent chains
for k in range(0, self.num_chains-1):
swap_proposal[k]= (lhood[k]/[1 if lhood[k+1] == 0 else lhood[k+1]])*(1/self.temperature[k] * 1/self.temperature[k+1])
#print(' before swap_proposal --------------------------------------+++++++++++++++++++++++=-')
for l in range( self.num_chains-1, 0, -1):
#u = 1
u = random.uniform(0, 1)
swap_prob = swap_proposal[l-1]
if u < swap_prob :
number_exchange[l] = number_exchange[l] +1
others = np.asarray([ lhood[l-1] ] )
para = np.concatenate([replica_param[l-1,:],others])
self.chain_parameters[l].put(para)
others = np.asarray([ lhood[l] ] )
param = np.concatenate([replica_param[l,:],others])
self.chain_parameters[l-1].put(param)
del para
del others
del param
else:
others = np.asarray([ lhood[l-1] ])
para = np.concatenate([replica_param[l-1,:],others])
self.chain_parameters[l-1].put(para)
others = np.asarray([ lhood[l] ])
param = np.concatenate([replica_param[l,:],others])
self.chain_parameters[l].put(param)
del para
del others
del param
del u
del swap_prob
#-------------------------------------------------------------------------------------
# resume suspended process
#-------------------------------------------------------------------------------------
for k in range (self.num_chains):
self.event[k].set()
#-------------------------------------------------------------------------------------
#check if all chains have completed runing
#-------------------------------------------------------------------------------------
count = 0
for i in range(self.num_chains):
if self.chains[i].is_alive() is False:
count+=1
while self.chain_parameters[i].empty() is False:
dummy = self.chain_parameters[i].get()
del dummy
if count == self.num_chains :
flag_running = False
del count
gc.collect() # fLet the main threag constantly be removing files from memory
#-------------------------------------------------------------------------------------
#wait for all processes to jin the main process
#-------------------------------------------------------------------------------------