-
Notifications
You must be signed in to change notification settings - Fork 33
/
inferences.py
2830 lines (2294 loc) · 125 KB
/
inferences.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
import copy
import logging
import numpy as np
from abc import ABCMeta, abstractmethod, abstractproperty
from scipy import optimize
from abcpy.acceptedparametersmanager import *
from abcpy.graphtools import GraphTools
from abcpy.jointapprox_lhd import ProductCombination
from abcpy.jointdistances import LinearCombination
from abcpy.output import Journal
from abcpy.perturbationkernel import DefaultKernel
from abcpy.probabilisticmodels import *
from abcpy.utils import cached
class InferenceMethod(GraphTools, 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
@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 backend(self):
"""To be overwritten by any sub-class: an attribute specifying the backend 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
class BaseMethodsWithKernel(metaclass = ABCMeta):
"""
This abstract base class represents inference methods that have a kernel.
"""
@abstractproperty
def kernel(self):
"""To be overwritten by any sub-class: an attribute specifying the transition or perturbation kernel."""
raise NotImplementedError
def perturb(self, column_index, epochs = 10, rng=np.random.RandomState()):
"""
Perturbs all free parameters, given the current weights.
Commonly used during inference.
Parameters
----------
column_index: integer
The index of the column in the accepted_parameters_bds that should be used for perturbation
epochs: integer
The number of times perturbation should happen before the algorithm is terminated
Returns
-------
boolean
Whether it was possible to set new parameter values for all probabilistic models
"""
current_epoch = 0
while current_epoch < epochs:
# Get new parameters of the graph
new_parameters = self.kernel.update(self.accepted_parameters_manager, column_index, rng=rng)
self._reset_flags()
# Order the parameters provided by the kernel in depth-first search order
correctly_ordered_parameters = self.get_correct_ordering(new_parameters)
# Try to set new parameters
accepted, last_index = self.set_parameters(correctly_ordered_parameters, 0)
if accepted:
break
current_epoch+=1
if current_epoch == 10:
return [False]
return [True, correctly_ordered_parameters]
class BaseLikelihood(InferenceMethod, BaseMethodsWithKernel, metaclass = ABCMeta):
"""
This abstract base class represents inference methods that use the likelihood.
"""
@abstractproperty
def likfun(self):
"""To be overwritten by any sub-class: an attribute specifying the likelihood function to be used."""
raise NotImplementedError
class BaseDiscrepancy(InferenceMethod, BaseMethodsWithKernel, metaclass = ABCMeta):
"""
This abstract base class represents inference methods using descrepancy.
"""
@abstractproperty
def distance(self):
"""To be overwritten by any sub-class: an attribute specifying the distance function."""
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: list
A list of the Probabilistic models corresponding to the observed datasets
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.
"""
# TODO: defining attributes as class attributes is not correct, move to init
model = None
distance = None
rng = None
n_samples = None
n_samples_per_param = None
epsilon = None
backend = None
def __init__(self, root_models, distances, backend, seed=None):
self.model = root_models
# We define the joint Linear combination distance using all the distances for each individual models
self.distance = LinearCombination(root_models, distances)
self.backend = backend
self.rng = np.random.RandomState(seed)
self.logger = logging.getLogger(__name__)
# An object managing the bds objects
self.accepted_parameters_manager = AcceptedParametersManager(self.model)
# counts the number of simulate calls
self.simulation_counter = 0
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: list
A list, containing lists describing the observed data sets
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.accepted_parameters_manager.broadcast(self.backend, 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_and_counter_pds = self.backend.map(self._sample_parameter, rng_pds)
accepted_parameters_and_counter = self.backend.collect(accepted_parameters_and_counter_pds)
accepted_parameters, counter = [list(t) for t in zip(*accepted_parameters_and_counter)]
for count in counter:
self.simulation_counter+=count
accepted_parameters = np.array(accepted_parameters)
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters)
journal.add_parameters(accepted_parameters)
journal.add_weights(np.ones((n_samples, 1)))
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters)
names_and_parameters = self._get_names_and_parameters()
journal.add_user_parameters(names_and_parameters)
journal.number_of_simulations.append(self.simulation_counter)
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
----------
rng: random number generator
The random number generator to be used.
Returns
-------
np.array
accepted parameter
"""
distance = self.distance.dist_max()
if distance < self.epsilon and self.logger:
self.logger.warn("initial epsilon {:e} is larger than dist_max {:e}"
.format(float(self.epsilon), distance))
theta = np.array(self.get_parameters(self.model)).reshape(-1,)
counter = 0
while distance > self.epsilon:
# Accept new parameter value if the distance is less than epsilon
self.sample_from_prior(rng=rng)
theta = np.array(self.get_parameters(self.model)).reshape(-1,)
y_sim = self.simulate(self.n_samples_per_param, rng=rng)
counter+=1
if(y_sim is not None):
distance = self.distance.distance(self.accepted_parameters_manager.observations_bds.value(), y_sim)
self.logger.debug("distance after {:4d} simulations: {:e}".format(
counter, distance))
else:
distance = self.distance.dist_max()
self.logger.debug(
"Needed {:4d} simulations to reach distance {:e} < epsilon = {:e}".
format(counter, distance, float(self.epsilon))
)
return (theta, counter)
class PMCABC(BaseDiscrepancy, 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 : list
A list of the Probabilistic models corresponding to the observed datasets
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
backend = None
def __init__(self, root_models, distances, backend, kernel=None, seed=None):
self.model = root_models
# We define the joint Linear combination distance using all the distances for each individual models
self.distance = LinearCombination(root_models, distances)
if(kernel is None):
mapping, garbage_index = self._get_mapping()
models = []
for mdl, mdl_index in mapping:
models.append(mdl)
kernel = DefaultKernel(models)
self.kernel = kernel
self.backend = backend
self.rng = np.random.RandomState(seed)
self.logger = logging.getLogger(__name__)
self.accepted_parameters_manager = AcceptedParametersManager(self.model)
self.simulation_counter=0
def sample(self, observations, steps, epsilon_init, n_samples = 10000, n_samples_per_param = 1, epsilon_percentile = 0, covFactor = 2, full_output=0, journal_file = None):
"""Samples from the posterior distribution of the model parameter given the observed
data observations.
Parameters
----------
observations : list
A list, containing lists describing the observed data sets
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.accepted_parameters_manager.broadcast(self.backend, observations)
self.n_samples = n_samples
self.n_samples_per_param=n_samples_per_param
if(journal_file is None):
journal = Journal(full_output)
journal.configuration["type_model"] = [type(model).__name__ for model in self.model]
journal.configuration["type_dist_func"] = type(self.distance).__name__
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
else:
journal = Journal.fromFile(journal_file)
accepted_parameters = None
accepted_weights = None
accepted_cov_mats = 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
self.logger.info("Starting PMC iterations")
for aStep in range(steps):
self.logger.debug("iteration {} of PMC algorithm".format(aStep))
if(aStep==0 and journal_file is not None):
accepted_parameters = journal.parameters[-1]
accepted_weights = journal.weights[-1]
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters, accepted_weights=accepted_weights)
kernel_parameters = []
for kernel in self.kernel.kernels:
kernel_parameters.append(
self.accepted_parameters_manager.get_accepted_parameters_bds_values(kernel.models))
self.accepted_parameters_manager.update_kernel_values(self.backend, kernel_parameters=kernel_parameters)
# 3: calculate covariance
self.logger.info("Calculateing covariance matrix")
new_cov_mats = self.kernel.calculate_cov(self.accepted_parameters_manager)
# Since each entry of new_cov_mats is a numpy array, we can multiply like this
accepted_cov_mats = [covFactor * new_cov_mat for new_cov_mat in new_cov_mats]
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.logger.info("Broadcasting parameters")
self.epsilon = epsilon_arr[aStep]
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters, accepted_weights, accepted_cov_mats)
# 1: calculate resample parameters
# print("INFO: Resampling parameters")
self.logger.info("Resamping parameters")
params_and_dists_and_ysim_and_counter_pds = self.backend.map(self._resample_parameter, rng_pds)
params_and_dists_and_ysim_and_counter = self.backend.collect(params_and_dists_and_ysim_and_counter_pds)
new_parameters, distances, counter = [list(t) for t in zip(*params_and_dists_and_ysim_and_counter)]
new_parameters = np.array(new_parameters)
#print(new_parameters)
for count in counter:
self.simulation_counter+=count
# Compute epsilon for next step
# print("INFO: Calculating acceptance threshold (epsilon).")
self.logger.info("Calculating acceptances threshold")
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
self.logger.info("Calculating weights")
new_parameters_pds = self.backend.parallelize(new_parameters)
self.logger.info("Calculate 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)
sum_of_weights = 0.0
for w in new_weights:
sum_of_weights += w
new_weights = new_weights / sum_of_weights
# The calculation of cov_mats needs the new weights and new parameters
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters = new_parameters, accepted_weights=new_weights)
# The parameters relevant to each kernel have to be used to calculate n_sample times. It is therefore more efficient to broadcast these parameters once, instead of collecting them at each kernel in each step
kernel_parameters = []
for kernel in self.kernel.kernels:
kernel_parameters.append(
self.accepted_parameters_manager.get_accepted_parameters_bds_values(kernel.models))
self.accepted_parameters_manager.update_kernel_values(self.backend, kernel_parameters=kernel_parameters)
# 3: calculate covariance
self.logger.info("Calculating covariance matrix")
new_cov_mats = self.kernel.calculate_cov(self.accepted_parameters_manager)
# Since each entry of new_cov_mats is a numpy array, we can multiply like this
new_cov_mats = [covFactor*new_cov_mat for new_cov_mat in new_cov_mats]
# 4: Update the newly computed values
accepted_parameters = new_parameters
accepted_weights = new_weights
accepted_cov_mats = new_cov_mats
self.logger.info("Save 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)
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters,
accepted_weights=accepted_weights)
names_and_parameters = self._get_names_and_parameters()
journal.add_user_parameters(names_and_parameters)
journal.number_of_simulations.append(self.simulation_counter)
# Add epsilon_arr to the journal
journal.configuration["epsilon_arr"] = epsilon_arr
return journal
# 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))
distance = self.distance.dist_max()
if distance < self.epsilon and self.logger:
self.logger.warn("initial epsilon {:e} is larger than dist_max {:e}"
.format(float(self.epsilon), distance))
theta = self.get_parameters()
counter=0
while distance > self.epsilon:
#print( " distance: " + str(distance) + " epsilon: " + str(self.epsilon))
if self.accepted_parameters_manager.accepted_parameters_bds == None:
self.sample_from_prior(rng=rng)
theta = self.get_parameters()
y_sim = self.simulate(self.n_samples_per_param, rng=rng)
counter+=1
else:
index = rng.choice(self.n_samples, size=1, p=self.accepted_parameters_manager.accepted_weights_bds.value().reshape(-1))
# 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:
perturbation_output = self.perturb(index[0], rng=rng)
if(perturbation_output[0] and self.pdf_of_prior(self.model, perturbation_output[1])!=0):
theta = perturbation_output[1]
break
y_sim = self.simulate(self.n_samples_per_param, rng=rng)
counter+=1
if(y_sim is not None):
distance = self.distance.distance(self.accepted_parameters_manager.observations_bds.value(),y_sim)
self.logger.debug("distance after {:4d} simulations: {:e}".format(
counter, distance))
else:
distance = self.distance.dist_max()
self.logger.debug(
"Needed {:4d} simulations to reach distance {:e} < epsilon = {:e}".
format(counter, distance, float(self.epsilon))
)
return (theta, distance, counter)
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
"""
self.logger.debug("_calculate_weight")
if self.accepted_parameters_manager.kernel_parameters_bds is None:
return 1.0 / self.n_samples
else:
prior_prob = self.pdf_of_prior(self.model, theta, 0)
denominator = 0.0
# Get the mapping of the models to be used by the kernels
mapping_for_kernels, garbage_index = self.accepted_parameters_manager.get_mapping(self.accepted_parameters_manager.model)
for i in range(0, self.n_samples):
pdf_value = self.kernel.pdf(mapping_for_kernels, self.accepted_parameters_manager, i, theta)
denominator += self.accepted_parameters_manager.accepted_weights_bds.value()[i, 0] * pdf_value
return 1.0 * prior_prob / denominator
class PMC(BaseLikelihood, 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 : list
A list of the Probabilistic models corresponding to the observed datasets
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
backend = None
def __init__(self, root_models, likfuns, backend, kernel=None, seed=None):
self.model = root_models
# We define the joint Product of likelihood functions using all the likelihoods for each individual models
self.likfun = ProductCombination(root_models, likfuns)
if(kernel is None):
mapping, garbage_index = self._get_mapping()
models = []
for mdl, mdl_index in mapping:
models.append(mdl)
kernel = DefaultKernel(models)
self.kernel = kernel
self.backend = backend
self.rng = np.random.RandomState(seed)
self.logger = logging.getLogger(__name__)
# these are usually big tables, so we broadcast them to have them once
# per executor instead of once per task
self.accepted_parameters_manager = AcceptedParametersManager(self.model)
self.simulation_counter = 0
def sample(self, observations, steps, n_samples = 10000, n_samples_per_param = 100, covFactors = None, iniPoints = None, full_output=0, journal_file = None):
"""Samples from the posterior distribution of the model parameter given the observed
data observations.
Parameters
----------
observations : list
A list, containing lists describing the observed data sets
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 : list of 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.sample_from_prior(rng=self.rng)
self.accepted_parameters_manager.broadcast(self.backend, observations)
self.n_samples = n_samples
self.n_samples_per_param = n_samples_per_param
if(journal_file is None):
journal = Journal(full_output)
journal.configuration["type_model"] = [type(model).__name__ for model in self.model]
journal.configuration["type_lhd_func"] = type(self.likfun).__name__
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"] = covFactors
journal.configuration["iniPoints"] = iniPoints
else:
journal = Journal.fromFile(journal_file)
accepted_parameters = None
accepted_weights = None
accepted_cov_mats = None
new_theta = None
dim = len(self.get_parameters())
# 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(rng=self.rng)
accepted_parameters[ind, :] = self.get_parameters()
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 covFactors is None:
covFactors = np.ones(shape=(len(self.kernel.kernels),))
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters, accepted_weights=accepted_weights)
# The parameters relevant to each kernel have to be used to calculate n_sample times. It is therefore more efficient to broadcast these parameters once, instead of collecting them at each kernel in each step
kernel_parameters = []
for kernel in self.kernel.kernels:
kernel_parameters.append(
self.accepted_parameters_manager.get_accepted_parameters_bds_values(kernel.models))
self.accepted_parameters_manager.update_kernel_values(self.backend, kernel_parameters=kernel_parameters)
# 3: calculate covariance
self.logger.info("Calculating covariance matrix")
new_cov_mats = self.kernel.calculate_cov(self.accepted_parameters_manager)
# Since each entry of new_cov_mats is a numpy array, we can multiply like this
accepted_cov_mats = [covFactor * new_cov_mat for covFactor, new_cov_mat in zip(covFactors,new_cov_mats)]
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_cov_mats=accepted_cov_mats)
# main SMC algorithm
self.logger.info("Starting pmc iterations")
for aStep in range(steps):
if(aStep==0 and journal_file is not None):
accepted_parameters = journal.parameters[-1]
accepted_weights = journal.weights[-1]
approx_likelihood_new_parameters = journal.opt_values[-1]
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters, accepted_weights=accepted_weights)
kernel_parameters = []
for kernel in self.kernel.kernels:
kernel_parameters.append(
self.accepted_parameters_manager.get_accepted_parameters_bds_values(kernel.models))
self.accepted_parameters_manager.update_kernel_values(self.backend, kernel_parameters=kernel_parameters)
# 3: calculate covariance
self.logger.info("Calculating covariance matrix")
new_cov_mats = self.kernel.calculate_cov(self.accepted_parameters_manager)
# Since each entry of new_cov_mats is a numpy array, we can multiply like this
accepted_cov_mats = [covFactor * new_cov_mat for covFactor, new_cov_mat in zip(covFactors, new_cov_mats)]
self.logger.info("Iteration {} of PMC algorithm".format(aStep))
# 0: update remotely required variables
self.logger.info("Broadcasting parameters")
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters, accepted_weights=accepted_weights, accepted_cov_mats=accepted_cov_mats)
# 1: calculate resample parameters
self.logger.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:
perturbation_output = self.perturb(index[ind], rng=self.rng)
if perturbation_output[0] and self.pdf_of_prior(self.model, perturbation_output[1])!= 0:
new_parameters[ind, :] = perturbation_output[1]
break
# 2: calculate approximate lieklihood for new parameters
self.logger.info("Calculate approximate likelihood")
merged_sim_data_parameter = self.flat_map(new_parameters, self.n_samples_per_param, self._simulate_data)
# Compute likelihood for each parameter value
approx_likelihood_new_parameters, counter = self.simple_map(merged_sim_data_parameter, self._approx_calc)
approx_likelihood_new_parameters = np.array(approx_likelihood_new_parameters).reshape(-1, 1)
for count in counter:
self.simulation_counter+=count
# 3: calculate new weights for new parameters
self.logger.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 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
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters, accepted_weights=new_weights)
# 4: calculate covariance
# The parameters relevant to each kernel have to be used to calculate n_sample times. It is therefore more efficient to broadcast these parameters once, instead of collecting them at each kernel in each step
self.logger.info("Calculating covariance matrix")
kernel_parameters = []
for kernel in self.kernel.kernels:
kernel_parameters.append(
self.accepted_parameters_manager.get_accepted_parameters_bds_values(kernel.models))
self.accepted_parameters_manager.update_kernel_values(self.backend, kernel_parameters=kernel_parameters)
# 3: calculate covariance
self.logger.info("Calculating covariance matrix")
new_cov_mats = self.kernel.calculate_cov(self.accepted_parameters_manager)
# Since each entry of new_cov_mats is a numpy array, we can multiply like this
new_cov_mats = [covFactor * new_cov_mat for covFactor, new_cov_mat in zip(covFactors, new_cov_mats)]
# 5: Update the newly computed values
accepted_parameters = new_parameters
accepted_weights = new_weights
accepted_cov_mat = new_cov_mats
self.logger.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)
journal.add_opt_values(approx_likelihood_new_parameters)
self.accepted_parameters_manager.update_broadcast(self.backend, accepted_parameters=accepted_parameters,
accepted_weights=accepted_weights)
names_and_parameters = self._get_names_and_parameters()
journal.add_user_parameters(names_and_parameters)
journal.number_of_simulations.append(self.simulation_counter)
return journal
## Simple_map and Flat_map: Python wrapper for nested parallelization
def simple_map(self, data, map_function):
data_pds = self.backend.parallelize(data)
result_pds = self.backend.map(map_function, data_pds)
result = self.backend.collect(result_pds)
main_result, counter = [list(t) for t in zip(*result)]
return main_result, counter
def flat_map(self, data, n_repeat, map_function):
repeated_data = np.repeat(data, n_repeat, axis=0)
repeated_data_pds = self.backend.parallelize(repeated_data)
repeated_data__result_pds = self.backend.map(map_function, repeated_data_pds)
repeated_data_result = self.backend.collect(repeated_data__result_pds)
repeated_data, result = [list(t) for t in zip(*repeated_data_result)]
merged_result_data = []
for ind in range(0, data.shape[0]):
merged_result_data.append([[[result[np.int(i)][0][0] \
for i in
np.where(np.mean(repeated_data == data[ind, :], axis=1) == 1)[0]]],
data[ind, :]])
return merged_result_data
# define helper functions for map step
def _simulate_data(self, theta):
"""
Simulate n_sample_per_param many datasets for new parameter
Parameters
----------
theta: numpy.ndarray
1xp matrix containing the model parameters, where p is the number of parameters
Returns
-------
(theta, sim_data)
tehta and simulate data
"""
# Simulate the fake data from the model given the parameter value theta
# print("DEBUG: Simulate model for parameter " + str(theta))
self.set_parameters(theta)
y_sim = self.simulate(1, self.rng)
return (theta, y_sim)
def _approx_calc(self, sim_data_parameter):
"""
Compute likelihood for new parameters using approximate likelihood function
Parameters
----------
sim_data_parameter: list
First element is the parameter and the second element is the simulated data
Returns
-------
float
The approximated likelihood function
"""
# Extract data and parameter
y_sim, theta = sim_data_parameter[0], sim_data_parameter[1]
# print("DEBUG: Extracting observation.")
obs = self.accepted_parameters_manager.observations_bds.value()
# print("DEBUG: Computing likelihood...")
total_pdf_at_theta = 1.
lhd = self.likfun.likelihood(obs, y_sim)
# print("DEBUG: Likelihood is :" + str(lhd))
pdf_at_theta = self.pdf_of_prior(self.model, theta)
total_pdf_at_theta *= (pdf_at_theta * lhd)
# print("DEBUG: prior pdf evaluated at theta is :" + str(pdf_at_theta))
return (total_pdf_at_theta, 1)
def _calculate_weight(self, theta):
"""
Calculates the weight for the given parameter using
accepted_parameters, accepted_cov_mat
Parameters
----------
theta: np.ndarray
1xp matrix containing the model parameters, where p is the number of parameters
Returns
-------
float
The new weight for theta
"""
self.logger.debug("_calculate_weight")
if self.accepted_parameters_manager.accepted_weights_bds is None:
return 1.0 / self.n_samples
else:
prior_prob = self.pdf_of_prior(self.model, theta)
denominator = 0.0
mapping_for_kernels, garbage_index = self.accepted_parameters_manager.get_mapping(
self.accepted_parameters_manager.model)
for i in range(0, self.n_samples):
pdf_value = self.kernel.pdf(mapping_for_kernels, self.accepted_parameters_manager, i, theta)
denominator+=self.accepted_parameters_manager.accepted_weights_bds.value()[i,0]*pdf_value
return 1.0 * prior_prob / denominator
class SABC(BaseDiscrepancy, InferenceMethod):
"""
This base class implements a modified version of Simulated Annealing Approximate Bayesian Computation (SABC) of [1] when the prior is non-informative.
[1] C. Albert, H. R. Kuensch and A. Scheidegger. A Simulated Annealing Approach to
Approximate Bayes Computations. Statistics and Computing, (2014).
Parameters
----------
model : list
A list of the Probabilistic models corresponding to the observed datasets
distance : abcpy.distances.Distance
Distance object defining the distance measure used 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