-
Notifications
You must be signed in to change notification settings - Fork 33
/
inferences_new.py
2644 lines (2235 loc) · 112 KB
/
inferences_new.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
from abc import ABCMeta, abstractmethod, abstractproperty
from ProbabilisticModel import *
import numpy as np
from abcpy.output import Journal
from scipy import optimize
#TODO check whether if we set a seed as well as an rng for the distributions, what happens.
#TODO check whether something like for j in range(self.parent.dimension) is done, since this will be wrong for hyperparameters
#NOTE since the output of discrete and continuous parameters is split, it will not necessarily give the correct order compared to the user input
"""
- This covariance matrix calculation is done assuming all the parameters are continuous. But if you have some of the parameters being discrete, then it breaks down.
- So for the moment do the following:
a) group continuous parameters and discrete parameters.
b) for continuous parameters do as we have done before. meaning computing cov matrix and providing that to multi-normal or muti-t to generate a new sample.
c) for discrete parameters, user should specify a distribution which can take the present values as input and give a discrete output.
"""
#NOTE since we still need the new_parameters_pds to calculate the cov matrix, we will probably need to split up our broadcast data in discrete and continuous. If we split this anyways, do we want there even to be an option to just give back the combined object, or only single ones? We could also implement set_continuous/set_discrete together with get of both, without set/get in total!
class InferenceMethod(metaclass = ABCMeta):
"""
This abstract base class represents an inference method.
"""
def __getstate__(self):
"""Cloudpickle is used with the MPIBackend. This function ensures that the backend itself
is not pickled
"""
state = self.__dict__.copy()
del state['backend']
return state
def sample_from_prior(self, models, rng=np.random.RandomState()):
"""
Samples values for the parameters of the specified model as well as all its parents.
Commonly used to sample new parameter values on the whole graph.
Parameters
----------
models: list of probabilistic models
Defines the models for which, together with their parents, new parameters will be sampled
rng: Random number generator to be used
Defines the random number generator to be used
"""
#all the parents of each model recursively sample new parameter values.
for model in models:
for parent in model.parents:
if(not(parent.visited)):
self.sample_from_prior([parent], rng=rng)
#each model itself samples new parameters
model.sample_parameters(rng=rng)
def _reset_flags(self, models):
"""
Resets all flags that say that a probabilistic model has been updated.
Commonly used after actions on the whole graph, to ensure that new actions can take place.
Parameters
----------
models: list of probabilistic models
The models for which, together with their parents, the flags should be reset.
"""
#for each model, the flags of the parents get reset recursively.
for model in models:
for parent in model.parents:
if(parent.visited):
self._reset_flags([parent])
model.visited = False
#NOTE not tested yet, not sure whether this works.
#TODO CHECK WHETHER THIS COVERS ALL 3 DIFFERENT CASES
def pdf_of_prior(self, models, parameters, index, is_root=True):
"""
Calculates the joint probability density function of the prior of the specified models at the given parameter values.
Commonly used to check whether new parameters are valid given the prior, as well as to calculate acceptance probabilities.
Parameters
----------
models: list of probabilistic models
Defines the models for which the pdf of their prior should be evaluated
parameters: python list
The parameters at which the pdf should be evaluated
index: integer
The current index to be considered within the parameters list
is_root: boolean
A flag specifying whether the provided models are the root models. This is to ensure that the pdf is calculated correctly.
Returns:
list
The resulting pdf, as well as the next index to be considered in the parameters list.
"""
result = [1.]*len(models)
for i, model in enumerate(models):
#if the model is not a root model, the pdf of this model, given the prior, should be calculated
if(not(is_root)):
helper = []
#this loop will skip hyperparameters, which doesn't matter due to our definition of the pdf
for j in range(model.dimension):
helper.append(parameters[index])
index+=1
if(len(helper)==1):
helper = helper[0]
else:
helper = np.array(helper)
result[i]*=model.pdf(helper)
#for each parent, the pdf of this parent has to be calculated as well.
for parent in model.parents:
pdf = self.pdf_of_prior([parent], parameters, index, is_root=False)
result[i]*=pdf[0][0]
index=pdf[1]
return [result, index]
def get_cont_disc_parameters(self, models):
"""
Returns the current values of all free parameters in the model.
Commonly used before perturbing the parameters of the model.
Parameters
----------
models: list of probabilistic models
The models for which, together with their parents, the parameter values should be returned
Returns
-------
list
Two lists, the first containing all continuous parameter values, the second containing all discrete parameter values.
"""
parameters_continuous = []
parameters_discrete = []
for model in models:
# append the current values of the free parameters of the model
for parameter in model.get_parameters():
if (isinstance(parameter, list)):
for param in parameter:
if(isinstance(model, Continuous)):
parameters_continuous.append(param)
else:
parameters_discrete.append(param)
else:
if(isinstance(model, Continuous)):
parameters_continuous.append(parameter)
else:
parameters_discrete.append(parameter)
# append the current values of the free parameters of each parent in order of a dfs.
for parent in model.parents:
if (not (parent.visited)):
parent_parameters_cont, parent_parameters_disc = self.get_parameters([parent])
for parameter in parent_parameters_cont:
if (isinstance(parameter, list)):
for param in parameter:
parameters_continuous.append(param)
else:
parameters_continuous.append(parameter)
for parameter in parent_parameters_disc:
if(isinstance(parameter, list)):
for param in parameter:
parameters_discrete.append(param)
else:
parameters_discrete.append(parameter)
# the parent nodes are marked as visited to avoid duplicated values
parent.visited = True
model.visited = True
return parameters_continuous, parameters_discrete
def get_parameters(self, models):
parameters_continuous, parameters_discrete = self._get_cont_disc_parameters(models)
parameters = []
for parameter in parameters_continuous:
parameters.append(parameter)
for parameter in parameters_discrete:
parameters.append(parameter)
return parameters
def number_of_continuous_parameters(self, models):
result = 0
for model in models:
if(isinstance(model, Continuous)):
result+=1
for parent in model.parents:
result+=self.number_of_continuous_parameters([parent])
parent.visited = True
model.visited = True
return result
#NOTE returns false iff we couldnt set some node, in that case, use the old parameters again to resample
def set_parameters(self, models, parameters, index_continuous, index_discrete):
"""
Sets the parameter values of the model, as well as of its parents, to the specified values.
Commonly used after perturbing the parameter values using a kernel.
Parameters
----------
model: list of probabilistic models
Defines all models for which, together with their parents, new values should be set
parameters: list
Defines the values to which the respective parameter values of the models should be set
index: integer
The current index to be considered in the parameters list
Returns
-------
boolean
Returns True iff it was possible to set the values for all models as well as their parents.
"""
for model in models:
if(isinstance(model, Continuous)):
#if possible, set the parameters of the current model to the appropriate values
if(not(model.set_parameters(parameters[index_continuous:model.number_of_free_parameters()]))):
return False
index_continuous+=model.dimension
else:
if(not(model.set_parameters(parameters[index_discrete:model.number_of_free_parameters()]))):
return False
index_discrete+=model.dimension
#set the parameters of each parent recursively, in order of dfs.
for parent in model.parents:
if(not(parent.visited)):
if(not(self.set_parameters([parent], parameters, index_continuous, index_discrete))):
return False
#marks set nodes as visited since values within the parameters list are not duplicated
parent.visited = True
model.visited = True
return True
@abstractmethod
def sample(self):
"""To be overwritten by any sub-class:
Samples from the posterior distribution of the model parameter given the observed
data observations.
"""
raise NotImplementedError
@abstractproperty
def model(self):
"""To be overwritten by any sub-class: an attribute specifying the model to be used
"""
raise NotImplementedError
@abstractproperty
def rng(self):
"""To be overwritten by any sub-class: an attribute specifying the random number generator to be used
"""
raise NotImplementedError
@abstractproperty
def n_samples(self):
"""To be overwritten by any sub-class: an attribute specifying the number of samples to be generated
"""
raise NotImplementedError
@abstractproperty
def n_samples_per_param(self):
"""To be overwritten by any sub-class: an attribute specifying the number of data points in each simulated data set."""
raise NotImplementedError
@abstractproperty
def observations_bds(self):
"""To be overwritten by any sub-class: an attribute saving the observations as bds
"""
raise NotImplementedError
class BasePMC(InferenceMethod, metaclass = ABCMeta):
"""
This abstract base class represents inference methods that use Population Monte Carlo.
"""
@abstractmethod
def _update_broadcasts(self, accepted_parameters, accepted_weights, accepted_cov_mat):
"""
To be overwritten by any sub-class: broadcasts visited values
Parameters
----------
accepted_parameters: numpy.array
Contains all new accepted parameters.
accepted_weights: numpy.array
Contains all the new accepted weights.
accepted_cov_mat: numpy.ndarray
Contains the new accepted covariance matrix
Returns
-------
None
"""
raise NotImplementedError
@abstractmethod
def _calculate_weight(self, theta):
"""
To be overwritten by any sub-class:
Calculates the weight for the given parameter using
accepted_parameters, accepted_cov_mat
Parameters
----------
theta: np.array
1xp matrix containing the model parameters, where p is the dimension of parameters
Returns
-------
float
the new weight for theta
"""
raise NotImplementedError
@abstractproperty
def kernel(self):
"""To be overwritten by any sub-class: an attribute specifying the kernel to be used
"""
raise NotImplementedError
@abstractproperty
def accepted_parameters_bds(self):
"""To be overwritten by any sub-class: an attribute saving the accepted parameters as bds
"""
raise NotImplementedError
@abstractproperty
def accepted_weights_bds(self):
"""To be overwritten by any sub-class: an attribute saving the accepted weights as bds
"""
raise NotImplementedError
@abstractproperty
def accepted_cov_mat_bds(self):
"""To be overwritten by any sub-class: an attribute saving the accepted covariance matrix as bds
"""
raise NotImplementedError
class BaseAnnealing(InferenceMethod, metaclass = ABCMeta):
"""
This abstract base class represents inference methods that use annealing.
"""
@abstractmethod
def _update_broadcasts(self):
raise NotImplementedError
@abstractmethod
def _accept_parameter(self):
raise NotImplementedError
@abstractproperty
def distance(self):
"""To be overwritten by any sub-class: an attribute specifying the distance measure to be used
"""
raise NotImplementedError
@abstractproperty
def kernel(self):
"""To be overwritten by any sub-class: an attribute specifying the kernel to be used
"""
raise NotImplementedError
@abstractproperty
def accepted_parameters_bds(self):
"""To be overwritten by any sub-class: an attribute saving the accepted parameters as bds
"""
raise NotImplementedError
@abstractproperty
def accepted_cov_mat_bds(self):
"""To be overwritten by any sub-class: an attribute saving the accepted covariance matrix as bds
"""
raise NotImplementedError
class BaseAdaptivePopulationMC(InferenceMethod, metaclass = ABCMeta):
"""
This abstract base class represents inference methods that use Adaptive Population Monte Carlo.
"""
@abstractmethod
def _update_broadcasts(self):
"""
To be overwritten by any sub-class: broadcasts visited values
Parameters
----------
accepted_parameters: numpy.array
Contains all new accepted parameters.
accepted_weights: numpy.array
Contains all the new accepted weights.
accepted_cov_mat: numpy.ndarray
Contains the new accepted covariance matrix
Returns
-------
None
"""
raise NotImplementedError
@abstractmethod
def _accept_parameter(self):
"""
To be overwritten by any sub-class:
Samples a single model parameter and simulate from it until
accepted with some probability.
"""
raise NotImplementedError
@abstractproperty
def distance(self):
"""To be overwritten by any sub-class: an attribute specifying the distance measure to be used
"""
raise NotImplementedError
@abstractproperty
def kernel(self):
"""To be overwritten by any sub-class: an attribute specifying the kernel to be used
"""
raise NotImplementedError
@abstractproperty
def accepted_parameters_bds(self):
"""To be overwritten by any sub-class: an attribute saving the accepted parameters as bds
"""
raise NotImplementedError
@abstractproperty
def accepted_cov_mat_bds(self):
"""To be overwritten by any sub-class: an attribute saving the accepted covariance matrix as bds
"""
raise NotImplementedError
class RejectionABC(InferenceMethod):
"""This base class implements the rejection algorithm based inference scheme [1] for
Approximate Bayesian Computation.
[1] Tavaré, S., Balding, D., Griffith, R., Donnelly, P.: Inferring coalescence
times from DNA sequence data. Genetics 145(2), 505–518 (1997).
Parameters
----------
model: abcpy.models.Model
Model object defining the model to be used.
distance: abcpy.distances.Distance
Distance object defining the distance measure to compare simulated and observed data sets.
backend: abcpy.backends.Backend
Backend object defining the backend to be used.
seed: integer, optional
Optional initial seed for the random number generator. The default value is generated randomly.
"""
model = None
distance = None
rng = None
n_samples = None
n_samples_per_param = None
epsilon = None
observations_bds = None
def __init__(self, model, distance, backend, seed=None):
self.model = model
self.distance = distance
self.backend = backend
self.rng = np.random.RandomState(seed)
def sample(self, observations, n_samples, n_samples_per_param, epsilon, full_output=0):
"""
Samples from the posterior distribution of the model parameter given the observed
data observations.
Parameters
----------
observations: numpy.ndarray
Observed data.
n_samples: integer
Number of samples to generate
n_samples_per_param: integer
Number of data points in each simulated data set.
epsilon: float
Value of threshold
full_output: integer, optional
If full_output==1, intermediate results are included in output journal.
The default value is 0, meaning the intermediate results are not saved.
Returns
-------
abcpy.output.Journal
a journal containing simulation results, metadata and optionally intermediate results.
"""
self.observations_bds = self.backend.broadcast(observations)
self.n_samples = n_samples
self.n_samples_per_param = n_samples_per_param
self.epsilon = epsilon
journal = Journal(full_output)
journal.configuration["n_samples"] = self.n_samples
journal.configuration["n_samples_per_param"] = self.n_samples_per_param
journal.configuration["epsilon"] = self.epsilon
accepted_parameters = None
# main Rejection ABC algorithm
seed_arr = self.rng.randint(1, n_samples * n_samples, size=n_samples, dtype=np.int32)
rng_arr = np.array([np.random.RandomState(seed) for seed in seed_arr])
rng_pds = self.backend.parallelize(rng_arr)
accepted_parameters_pds = self.backend.map(self._sample_parameter, rng_pds)
accepted_parameters = self.backend.collect(accepted_parameters_pds)
accepted_parameters = np.array(accepted_parameters)
journal.add_parameters(accepted_parameters)
journal.add_weights(np.ones((n_samples, 1)))
return journal
def _sample_parameter(self, rng):
"""
Samples a single model parameter and simulates from it until
distance between simulated outcome and the observation is
smaller than epsilon.
Parameters
----------
seed: int
value of a seed to be used for reseeding
Returns
-------
np.array
accepted parameter
"""
distance = self.distance.dist_max()
while distance > self.epsilon:
# Accept new parameter value if the distance is less than epsilon
self.sample_from_prior(self.model, rng=rng)
self._reset_flags(self.model)
#TODO WHAT SHOULD HAPPEN IF WE HAVE MORE THAN ONE MODEL
#NOTE this gives reasonable values for the y_sim. However, the distances are very large, possibly because of the algorithm used, not sure
y_sim = self.model[0].sample_from_distribution(self.n_samples_per_param, rng=rng).tolist()
distance = self.distance.distance(self.observations_bds.value(), y_sim)
#print(distance)
return self.get_parameters(self.model)
class PMCABC(BasePMC, InferenceMethod):
"""
This base class implements a modified version of Population Monte Carlo based inference scheme
for Approximate Bayesian computation of Beaumont et. al. [1]. Here the threshold value at `t`-th generation are adaptively chosen
by taking the maximum between the epsilon_percentile-th value of discrepancies of the accepted
parameters at `t-1`-th generation and the threshold value provided for this generation by the user. If we take the
value of epsilon_percentile to be zero (default), this method becomes the inference scheme described in [1], where
the threshold values considered at each generation are the ones provided by the user.
[1] M. A. Beaumont. Approximate Bayesian computation in evolution and ecology. Annual Review of Ecology,
Evolution, and Systematics, 41(1):379–406, Nov. 2010.
Parameters
----------
model : abcpy.models.Model
Model object defining the model to be used.
distance : abcpy.distances.Distance
Distance object defining the distance measure to compare simulated and observed data sets.
kernel : abcpy.distributions.Distribution
Distribution object defining the perturbation kernel needed for the sampling.
backend : abcpy.backends.Backend
Backend object defining the backend to be used.
seed : integer, optional
Optional initial seed for the random number generator. The default value is generated randomly.
"""
model = None
distance = None
kernel = None
rng = None
#default value, set so that testing works
n_samples = 2
n_samples_per_param = None
observations_bds = None
accepted_parameters_bds = None
accepted_weights_bds = None
accepted_cov_mat_bds = None
def __init__(self, model, distance, kernel, backend, seed=None):
self.model = model
self.distance = distance
self.kernel = kernel
self.backend = backend
self.rng = np.random.RandomState(seed)
# these are usually big tables, so we broadcast them to have them once
# per executor instead of once per task
self.observations_bds = None
self.accepted_parameters_bds = None
self.accepted_weights_bds = None
self.accepted_cov_mat_bds = None
def sample(self, observations, steps, epsilon_init, n_samples = 10000, n_samples_per_param = 1, epsilon_percentile = 0, covFactor = 2, full_output=0):
"""Samples from the posterior distribution of the model parameter given the observed
data observations.
Parameters
----------
observations : numpy.ndarray
Observed data.
steps : integer
Number of iterations in the sequential algoritm ("generations")
epsilon_init : numpy.ndarray
An array of proposed values of epsilon to be used at each steps. Can be supplied
A single value to be used as the threshold in Step 1 or a `steps`-dimensional array of values to be
used as the threshold in evry steps.
n_samples : integer, optional
Number of samples to generate. The default value is 10000.
n_samples_per_param : integer, optional
Number of data points in each simulated data set. The default value is 1.
epsilon_percentile : float, optional
A value between [0, 100]. The default value is 0, meaning the threshold value provided by the user being used.
covFactor : float, optional
scaling parameter of the covariance matrix. The default value is 2 as considered in [1].
full_output: integer, optional
If full_output==1, intermediate results are included in output journal.
The default value is 0, meaning the intermediate results are not saved.
Returns
-------
abcpy.output.Journal
A journal containing simulation results, metadata and optionally intermediate results.
"""
self.observations_bds = self.backend.broadcast(observations)
self.n_samples = n_samples
self.n_samples_per_param=n_samples_per_param
journal = Journal(full_output)
journal.configuration["type_model"] = type(self.model)
journal.configuration["type_dist_func"] = type(self.distance)
journal.configuration["n_samples"] = self.n_samples
journal.configuration["n_samples_per_param"] = self.n_samples_per_param
journal.configuration["steps"] = steps
journal.configuration["epsilon_percentile"] = epsilon_percentile
accepted_parameters = None
accepted_weights = None
accepted_cov_mat = None
# Define epsilon_arr
if len(epsilon_init) == steps:
epsilon_arr = epsilon_init
else:
if len(epsilon_init) == 1:
epsilon_arr = [None] * steps
epsilon_arr[0] = epsilon_init
else:
raise ValueError("The length of epsilon_init can only be equal to 1 or steps.")
# main PMCABC algorithm
# print("INFO: Starting PMCABC iterations.")
for aStep in range(0, steps):
# print("DEBUG: Iteration " + str(aStep) + " of PMCABC algorithm.")
seed_arr = self.rng.randint(0, np.iinfo(np.uint32).max, size=n_samples, dtype=np.uint32)
rng_arr = np.array([np.random.RandomState(seed) for seed in seed_arr])
rng_pds = self.backend.parallelize(rng_arr)
# 0: update remotely required variables
# print("INFO: Broadcasting parameters.")
self.epsilon = epsilon_arr[aStep]
self._update_broadcasts(accepted_parameters, accepted_weights, accepted_cov_mat)
# 1: calculate resample parameters
# print("INFO: Resampling parameters")
params_and_dists_and_ysim_pds = self.backend.map(self._resample_parameter, rng_pds)
params_and_dists_and_ysim = self.backend.collect(params_and_dists_and_ysim_pds)
new_parameters, distances = [list(t) for t in zip(*params_and_dists_and_ysim)]
new_parameters = np.array(new_parameters)
self._update_broadcasts(accepted_parameters, accepted_weights, accepted_cov_mat)
# Compute epsilon for next step
# print("INFO: Calculating acceptance threshold (epsilon).")
if aStep < steps - 1:
if epsilon_arr[aStep + 1] == None:
epsilon_arr[aStep + 1] = np.percentile(distances, epsilon_percentile)
else:
epsilon_arr[aStep + 1] = np.max(
[np.percentile(distances, epsilon_percentile), epsilon_arr[aStep + 1]])
# 2: calculate weights for new parameters
# print("INFO: Calculating weights.")
new_parameters_pds = self.backend.parallelize(new_parameters)
new_weights_pds = self.backend.map(self._calculate_weight, new_parameters_pds)
new_weights = np.array(self.backend.collect(new_weights_pds)).reshape(-1, 1)
sum_of_weights = 0.0
for w in new_weights:
sum_of_weights += w
new_weights = new_weights / sum_of_weights
# 3: calculate covariance
# print("INFO: Calculating covariance matrix.")
new_cov_mat = covFactor * np.cov(new_parameters, aweights=new_weights.reshape(-1), rowvar=False)
# 4: Update the newly computed values
accepted_parameters = new_parameters
accepted_weights = new_weights
accepted_cov_mat = new_cov_mat
# print("INFO: Saving configuration to output journal.")
if (full_output == 1 and aStep <= steps - 1) or (full_output == 0 and aStep == steps - 1):
journal.add_parameters(accepted_parameters)
journal.add_weights(accepted_weights)
# Add epsilon_arr to the journal
journal.configuration["epsilon_arr"] = epsilon_arr
return journal
def _update_broadcasts(self, accepted_parameters, accepted_weights, accepted_cov_mat):
def destroy(bc):
if bc != None:
bc.unpersist
# bc.destroy
if not accepted_parameters is None:
self.accepted_parameters_bds = self.backend.broadcast(accepted_parameters)
if not accepted_weights is None:
self.accepted_weights_bds = self.backend.broadcast(accepted_weights)
if not accepted_cov_mat is None:
self.accepted_cov_mat_bds = self.backend.broadcast(accepted_cov_mat)
# define helper functions for map step
def _resample_parameter(self, rng):
"""
Samples a single model parameter and simulate from it until
distance between simulated outcome and the observation is
smaller than epsilon.
Parameters
----------
seed: integer
initial seed for the random number generator.
Returns
-------
np.array
accepted parameter
"""
rng.seed(rng.randint(np.iinfo(np.uint32).max, dtype=np.uint32))
self.kernel.rng.seed(rng.randint(np.iinfo(np.uint32).max, dtype=np.uint32))
distance = self.distance.dist_max()
while distance > self.epsilon:
# print("on seed " + str(seed) + " distance: " + str(distance) + " epsilon: " + str(self.epsilon))
if self.accepted_parameters_bds == None:
self.sample_from_prior(self.model, rng=rng)
self._reset_flags(self.model)
theta = self.get_parameters(self.model)
self._reset_flags(self.model)
else:
index = rng.choice(self.n_samples, size=1, p=self.accepted_weights_bds.value().reshape(-1))
theta = self.accepted_parameters_bds.value()[index[0]]
# truncate the normal to the bounds of parameter space of the model
# truncating the normal like this is fine: https://arxiv.org/pdf/0907.4010v1.pdf
while True:
new_theta = self.kernel.perturb(theta, self.accepted_cov_mat_bds.value())
theta_is_accepted = self.set_parameters(self.model, new_theta, 0)
self._reset_flags(self.model)
if theta_is_accepted and self.pdf_of_prior(self.model, new_theta, 0)[0][0] != 0:
break
#TODO WHAT IF MORE THAN 1 MODEL
y_sim = self.model[0].sample_from_distribution(self.n_samples_per_param, rng=rng).tolist()
distance = self.distance.distance(self.observations_bds.value(), y_sim)
return (theta, distance)
def _calculate_weight(self, theta):
"""
Calculates the weight for the given parameter using
accepted_parameters, accepted_cov_mat
Parameters
----------
theta: np.array
1xp matrix containing model parameter, where p is the number of parameters
Returns
-------
float
the new weight for theta
"""
if self.accepted_weights_bds is None:
return 1.0 / self.n_samples
else:
prior_prob = self.pdf_of_prior(self.model, theta, 0)[0][0] #first [0] because it returns a list, second [0] because if we have multiple models
denominator = 0.0
for i in range(0, self.n_samples):
pdf_value = self.kernel.pdf(self.accepted_parameters_bds.value()[i,:], self.accepted_cov_mat_bds.value(), theta)
denominator += self.accepted_weights_bds.value()[i, 0] * pdf_value
return 1.0 * prior_prob / denominator
class PMC(BasePMC, InferenceMethod):
"""
Population Monte Carlo based inference scheme of Cappé et. al. [1].
This algorithm assumes a likelihood function is available and can be evaluated
at any parameter value given the oberved dataset. In absence of the
likelihood function or when it can't be evaluated with a rational
computational expenses, we use the approximated likelihood functions in
abcpy.approx_lhd module, for which the argument of the consistency of the
inference schemes are based on Andrieu and Roberts [2].
[1] Cappé, O., Guillin, A., Marin, J.-M., and Robert, C. P. (2004). Population Monte Carlo.
Journal of Computational and Graphical Statistics, 13(4), 907–929.
[2] C. Andrieu and G. O. Roberts. The pseudo-marginal approach for efficient Monte Carlo computations.
Annals of Statistics, 37(2):697–725, 04 2009.
Parameters
----------
model : abcpy.models.Model
Model object defining the model to be used.
likfun : abcpy.approx_lhd.Approx_likelihood
Approx_likelihood object defining the approximated likelihood to be used.
kernel : abcpy.distributions.Distribution
Distribution object defining the perturbation kernel needed for the sampling.
backend : abcpy.backends.Backend
Backend object defining the backend to be used.
seed : integer, optional
Optional initial seed for the random number generator. The default value is generated randomly.
"""
model = None
likfun = None
kernel = None
rng = None
n_samples = None
n_samples_per_param = None
observations_bds = None
accepted_parameters_bds = None
accepted_weights_bds = None
accepted_cov_mat_bds = None
def __init__(self, model, likfun, kernel, backend, seed=None):
self.model = model
self.likfun = likfun
self.kernel = kernel
self.backend = backend
self.rng = np.random.RandomState(seed)
# these are usually big tables, so we broadcast them to have them once
# per executor instead of once per task
self.observations_bds = None
self.accepted_parameters_bds = None
self.accepted_weights_bds = None
self.accepted_cov_mat_bds = None
def sample(self, observations, steps, n_samples = 10000, n_samples_per_param = 100, covFactor = None, iniPoints = None, full_output=0):
"""Samples from the posterior distribution of the model parameter given the observed
data observations.
Parameters
----------
observations : python list
Observed data
steps : integer
number of iterations in the sequential algoritm ("generations")
n_samples : integer, optional
number of samples to generate. The default value is 10000.
n_samples_per_param : integer, optional
number of data points in each simulated data set. The default value is 100.
covFactor : float, optional
scaling parameter of the covariance matrix. The default is a p dimensional array of 1 when p is the dimension of the parameter.
inipoints : numpy.ndarray, optional
parameter vaulues from where the sampling starts. By default sampled from the prior.
full_output: integer, optional
If full_output==1, intermediate results are included in output journal.
The default value is 0, meaning the intermediate results are not saved.
Returns
-------
abcpy.output.Journal
A journal containing simulation results, metadata and optionally intermediate results.
"""
self.observations_bds = self.backend.broadcast(observations)
self.n_samples = n_samples
self.n_samples_per_param = n_samples_per_param
journal = Journal(full_output)
journal.configuration["type_model"] = type(self.model)
journal.configuration["type_lhd_func"] = type(self.likfun)
journal.configuration["n_samples"] = self.n_samples
journal.configuration["n_samples_per_param"] = self.n_samples_per_param
journal.configuration["steps"] = steps
journal.configuration["covFactor"] = covFactor
journal.configuration["iniPoints"] = iniPoints
accepted_parameters = None
accepted_weights = None
accepted_cov_mat = None
new_theta = None
dim = len(self.get_parameters(self.model))
self._reset_flags(self.model)
# Initialize particles: When not supplied, randomly draw them from prior distribution
# Weights of particles: Assign equal weights for each of the particles
if iniPoints == None:
accepted_parameters = np.zeros(shape=(n_samples, dim))
for ind in range(0, n_samples):
self.sample_from_prior(self.model, rng=self.rng)
self._reset_flags(self.model)
accepted_parameters[ind, :] = self.get_parameters(self.model)
self._reset_flags(self.model)
accepted_weights = np.ones((n_samples, 1), dtype=np.float) / n_samples
else:
accepted_parameters = iniPoints
accepted_weights = np.ones((iniPoints.shape[0], 1), dtype=np.float) / iniPoints.shape[0]
if covFactor is None:
covFactor = np.ones(shape=(dim,))
# Calculate initial covariance matrix
accepted_cov_mat = covFactor * np.cov(accepted_parameters, aweights=accepted_weights.reshape(-1), rowvar=False)
# main SMC algorithm
# print("INFO: Starting PMC iterations.")
for aStep in range(0, steps):
# print("DEBUG: Iteration " + str(aStep) + " of PMC algorithm.")
# 0: update remotely required variables
# print("INFO: Broadcasting parameters.")
self._update_broadcasts(accepted_parameters, accepted_weights, accepted_cov_mat)
# 1: calculate resample parameters
# print("INFO: Resample parameters.")
index = self.rng.choice(accepted_parameters.shape[0], size=n_samples, p=accepted_weights.reshape(-1))
# Choose a new particle using the resampled particle (make the boundary proper)
# Initialize new_parameters
new_parameters = np.zeros((n_samples, dim), dtype=np.float)
for ind in range(0, self.n_samples):
while True:
new_theta = self.kernel.perturb(accepted_parameters[index[ind],:],accepted_cov_mat)
theta_is_accepted = self.set_parameters(self.model, new_theta, 0)
self._reset_flags(self.model)
if theta_is_accepted and self.pdf_of_prior(self.model, new_theta, 0)[0][0] != 0:
new_parameters[ind, :] = new_theta
break
# 2: calculate approximate lieklihood for new parameters
# print("INFO: Calculate approximate likelihood.")
new_parameters_pds = self.backend.parallelize(new_parameters)
approx_likelihood_new_parameters_pds = self.backend.map(self._approx_lik_calc, new_parameters_pds)
# print("DEBUG: Collect approximate likelihood from pds.")
approx_likelihood_new_parameters = np.array(
self.backend.collect(approx_likelihood_new_parameters_pds)).reshape(-1, 1)
# 3: calculate new weights for new parameters
# print("INFO: Calculating weights.")
new_weights_pds = self.backend.map(self._calculate_weight, new_parameters_pds)
new_weights = np.array(self.backend.collect(new_weights_pds)).reshape(-1, 1)
#NOTE this loop can give 0, for example if the example + synliklihood are used!
sum_of_weights = 0.0
for i in range(0, self.n_samples):
new_weights[i] = new_weights[i] * approx_likelihood_new_parameters[i]
sum_of_weights += new_weights[i]
new_weights = new_weights / sum_of_weights
accepted_parameters = new_parameters
# 4: calculate covariance
# print("INFO: Calculating covariance matrix.")
new_cov_mat = covFactor * np.cov(accepted_parameters, aweights=accepted_weights.reshape(-1), rowvar=False)
# 5: Update the newly computed values
accepted_parameters = new_parameters
accepted_weights = new_weights
accepted_cov_mat = new_cov_mat