CUQIpy 1.4.0.post0.dev13__py3-none-any.whl → 1.4.0.post0.dev41__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of CUQIpy might be problematic. Click here for more details.
- cuqi/__init__.py +1 -0
- cuqi/_version.py +3 -3
- cuqi/experimental/__init__.py +1 -2
- cuqi/experimental/_recommender.py +4 -4
- cuqi/legacy/__init__.py +2 -0
- cuqi/legacy/sampler/__init__.py +11 -0
- cuqi/legacy/sampler/_conjugate.py +55 -0
- cuqi/legacy/sampler/_conjugate_approx.py +52 -0
- cuqi/legacy/sampler/_cwmh.py +196 -0
- cuqi/legacy/sampler/_gibbs.py +231 -0
- cuqi/legacy/sampler/_hmc.py +335 -0
- cuqi/legacy/sampler/_langevin_algorithm.py +198 -0
- cuqi/legacy/sampler/_laplace_approximation.py +184 -0
- cuqi/legacy/sampler/_mh.py +190 -0
- cuqi/legacy/sampler/_pcn.py +244 -0
- cuqi/legacy/sampler/_rto.py +284 -0
- cuqi/legacy/sampler/_sampler.py +182 -0
- cuqi/problem/_problem.py +87 -80
- cuqi/sampler/__init__.py +120 -8
- cuqi/sampler/_conjugate.py +376 -35
- cuqi/sampler/_conjugate_approx.py +40 -16
- cuqi/sampler/_cwmh.py +132 -138
- cuqi/{experimental/mcmc → sampler}/_direct.py +1 -1
- cuqi/sampler/_gibbs.py +269 -130
- cuqi/sampler/_hmc.py +328 -201
- cuqi/sampler/_langevin_algorithm.py +282 -98
- cuqi/sampler/_laplace_approximation.py +87 -117
- cuqi/sampler/_mh.py +47 -157
- cuqi/sampler/_pcn.py +56 -211
- cuqi/sampler/_rto.py +206 -140
- cuqi/sampler/_sampler.py +540 -135
- {cuqipy-1.4.0.post0.dev13.dist-info → cuqipy-1.4.0.post0.dev41.dist-info}/METADATA +1 -1
- {cuqipy-1.4.0.post0.dev13.dist-info → cuqipy-1.4.0.post0.dev41.dist-info}/RECORD +36 -35
- cuqi/experimental/mcmc/__init__.py +0 -122
- cuqi/experimental/mcmc/_conjugate.py +0 -396
- cuqi/experimental/mcmc/_conjugate_approx.py +0 -76
- cuqi/experimental/mcmc/_cwmh.py +0 -190
- cuqi/experimental/mcmc/_gibbs.py +0 -366
- cuqi/experimental/mcmc/_hmc.py +0 -462
- cuqi/experimental/mcmc/_langevin_algorithm.py +0 -382
- cuqi/experimental/mcmc/_laplace_approximation.py +0 -154
- cuqi/experimental/mcmc/_mh.py +0 -80
- cuqi/experimental/mcmc/_pcn.py +0 -89
- cuqi/experimental/mcmc/_rto.py +0 -350
- cuqi/experimental/mcmc/_sampler.py +0 -582
- {cuqipy-1.4.0.post0.dev13.dist-info → cuqipy-1.4.0.post0.dev41.dist-info}/WHEEL +0 -0
- {cuqipy-1.4.0.post0.dev13.dist-info → cuqipy-1.4.0.post0.dev41.dist-info}/licenses/LICENSE +0 -0
- {cuqipy-1.4.0.post0.dev13.dist-info → cuqipy-1.4.0.post0.dev41.dist-info}/top_level.txt +0 -0
cuqi/sampler/_gibbs.py
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
|
-
from cuqi.distribution import JointDistribution
|
|
1
|
+
from cuqi.distribution import JointDistribution, Posterior
|
|
2
2
|
from cuqi.sampler import Sampler
|
|
3
|
-
from cuqi.samples import Samples
|
|
4
|
-
from typing import Dict
|
|
3
|
+
from cuqi.samples import Samples, JointSamples
|
|
4
|
+
from typing import Dict
|
|
5
5
|
import numpy as np
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
import warnings
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from tqdm import tqdm
|
|
10
|
+
except ImportError:
|
|
11
|
+
def tqdm(iterable, **kwargs):
|
|
12
|
+
warnings.warn("Module mcmc: tqdm not found. Install tqdm to get sampling progress.")
|
|
13
|
+
return iterable
|
|
14
|
+
|
|
15
|
+
# Not subclassed from Sampler as Gibbs handles multiple samplers and samples multiple parameters
|
|
16
|
+
# Similar approach as for JointDistribution
|
|
17
|
+
class HybridGibbs:
|
|
10
18
|
"""
|
|
11
|
-
Gibbs sampler for sampling a joint distribution.
|
|
19
|
+
Hybrid Gibbs sampler for sampling a joint distribution.
|
|
12
20
|
|
|
13
21
|
Gibbs sampling samples the variables of the distribution sequentially,
|
|
14
22
|
one variable at a time. When a variable represents a random vector, the
|
|
@@ -17,7 +25,24 @@ class Gibbs:
|
|
|
17
25
|
The sampling of each variable is done by sampling from the conditional
|
|
18
26
|
distribution of that variable given the values of the other variables.
|
|
19
27
|
This is often a very efficient way of sampling from a joint distribution
|
|
20
|
-
if the conditional distributions are easy to sample from.
|
|
28
|
+
if the conditional distributions are easy to sample from.
|
|
29
|
+
|
|
30
|
+
Hybrid Gibbs sampler is a generalization of the Gibbs sampler where the
|
|
31
|
+
conditional distributions are sampled using different MCMC samplers.
|
|
32
|
+
|
|
33
|
+
When the conditionals are sampled exactly, the samples from the Gibbs
|
|
34
|
+
sampler converge to the joint distribution. See e.g.
|
|
35
|
+
Gelman et al. "Bayesian Data Analysis" (2014), Third Edition
|
|
36
|
+
for more details.
|
|
37
|
+
|
|
38
|
+
In each Gibbs step, the corresponding sampler state and history are stored,
|
|
39
|
+
then the sampler is reinitialized. After reinitialization, the sampler state
|
|
40
|
+
and history are set back to the stored values. This ensures preserving the
|
|
41
|
+
statefulness of the samplers.
|
|
42
|
+
|
|
43
|
+
The order in which the conditionals are sampled is the order of the
|
|
44
|
+
variables in the sampling strategy, unless a different sampling order
|
|
45
|
+
is specified by the parameter `scan_order`
|
|
21
46
|
|
|
22
47
|
Parameters
|
|
23
48
|
----------
|
|
@@ -25,10 +50,25 @@ class Gibbs:
|
|
|
25
50
|
Target distribution to sample from.
|
|
26
51
|
|
|
27
52
|
sampling_strategy : dict
|
|
28
|
-
Dictionary of sampling strategies for each
|
|
29
|
-
Keys are
|
|
53
|
+
Dictionary of sampling strategies for each variable.
|
|
54
|
+
Keys are variable names.
|
|
30
55
|
Values are sampler objects.
|
|
31
56
|
|
|
57
|
+
num_sampling_steps : dict, *optional*
|
|
58
|
+
Dictionary of number of sampling steps for each variable.
|
|
59
|
+
The sampling steps are defined as the number of times the sampler
|
|
60
|
+
will call its step method in each Gibbs step.
|
|
61
|
+
Default is 1 for all variables.
|
|
62
|
+
|
|
63
|
+
scan_order : list or str, *optional*
|
|
64
|
+
Order in which the conditional distributions are sampled.
|
|
65
|
+
If set to "random", use a random ordering at each step.
|
|
66
|
+
If not specified, it will be the order in the sampling_strategy.
|
|
67
|
+
|
|
68
|
+
callback : callable, optional
|
|
69
|
+
A function that will be called after each sampling step. It can be useful for monitoring the sampler during sampling.
|
|
70
|
+
The function should take three arguments: the sampler object, the index of the current sampling step, the total number of requested samples. The last two arguments are integers. An example of the callback function signature is: `callback(sampler, sample_index, num_of_samples)`.
|
|
71
|
+
|
|
32
72
|
Example
|
|
33
73
|
-------
|
|
34
74
|
.. code-block:: python
|
|
@@ -37,7 +77,7 @@ class Gibbs:
|
|
|
37
77
|
import numpy as np
|
|
38
78
|
|
|
39
79
|
# Model and data
|
|
40
|
-
A, y_obs, probinfo = cuqi.testproblem.Deconvolution1D(phantom='
|
|
80
|
+
A, y_obs, probinfo = cuqi.testproblem.Deconvolution1D(phantom='sinc').get_components()
|
|
41
81
|
n = A.domain_dim
|
|
42
82
|
|
|
43
83
|
# Define distributions
|
|
@@ -52,15 +92,20 @@ class Gibbs:
|
|
|
52
92
|
|
|
53
93
|
# Define sampling strategy
|
|
54
94
|
sampling_strategy = {
|
|
55
|
-
'x': cuqi.sampler.LinearRTO,
|
|
56
|
-
|
|
95
|
+
'x': cuqi.sampler.LinearRTO(maxit=15),
|
|
96
|
+
'd': cuqi.sampler.Conjugate(),
|
|
97
|
+
'l': cuqi.sampler.Conjugate(),
|
|
57
98
|
}
|
|
58
99
|
|
|
59
100
|
# Define Gibbs sampler
|
|
60
|
-
sampler = cuqi.sampler.
|
|
101
|
+
sampler = cuqi.sampler.HybridGibbs(posterior, sampling_strategy)
|
|
61
102
|
|
|
62
103
|
# Run sampler
|
|
63
|
-
|
|
104
|
+
sampler.warmup(200)
|
|
105
|
+
sampler.sample(1000)
|
|
106
|
+
|
|
107
|
+
# Get samples removing burn-in
|
|
108
|
+
samples = sampler.get_samples().burnthin(200)
|
|
64
109
|
|
|
65
110
|
# Plot results
|
|
66
111
|
samples['x'].plot_ci(exact=probinfo.exactSolution)
|
|
@@ -69,159 +114,253 @@ class Gibbs:
|
|
|
69
114
|
|
|
70
115
|
"""
|
|
71
116
|
|
|
72
|
-
def __init__(self, target: JointDistribution, sampling_strategy: Dict[
|
|
117
|
+
def __init__(self, target: JointDistribution, sampling_strategy: Dict[str, Sampler], num_sampling_steps: Dict[str, int] = None, scan_order = None, callback=None):
|
|
73
118
|
|
|
74
119
|
# Store target and allow conditioning to reduce to a single density
|
|
75
120
|
self.target = target() # Create a copy of target distribution (to avoid modifying the original)
|
|
76
121
|
|
|
77
|
-
#
|
|
78
|
-
self.samplers =
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
self.samplers[par_name_] = sampling_strategy[par_name]
|
|
83
|
-
else:
|
|
84
|
-
self.samplers[par_name] = sampling_strategy[par_name]
|
|
122
|
+
# Store sampler instances (again as a copy to avoid modifying the original)
|
|
123
|
+
self.samplers = sampling_strategy.copy()
|
|
124
|
+
|
|
125
|
+
# Store number of sampling steps for each parameter
|
|
126
|
+
self.num_sampling_steps = num_sampling_steps
|
|
85
127
|
|
|
86
128
|
# Store parameter names
|
|
87
129
|
self.par_names = self.target.get_parameter_names()
|
|
88
130
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
131
|
+
# Store the scan order
|
|
132
|
+
self._scan_order = scan_order
|
|
133
|
+
|
|
134
|
+
# Check that the parameters of the target align with the sampling_strategy and scan_order
|
|
135
|
+
if set(self.par_names) != set(self.scan_order):
|
|
136
|
+
raise ValueError("Parameter names in JointDistribution do not equal the names in the scan order.")
|
|
137
|
+
|
|
138
|
+
# Initialize sampler (after target is set)
|
|
139
|
+
self._initialize()
|
|
140
|
+
|
|
141
|
+
# Set the callback function
|
|
142
|
+
self.callback = callback
|
|
143
|
+
|
|
144
|
+
def _initialize(self):
|
|
145
|
+
""" Initialize sampler """
|
|
92
146
|
|
|
93
147
|
# Initial points
|
|
94
|
-
current_samples = self._get_initial_points()
|
|
148
|
+
self.current_samples = self._get_initial_points()
|
|
95
149
|
|
|
96
|
-
#
|
|
97
|
-
|
|
98
|
-
at_Ns = self._Ns
|
|
150
|
+
# Initialize sampling steps
|
|
151
|
+
self._initialize_num_sampling_steps()
|
|
99
152
|
|
|
100
|
-
# Allocate
|
|
101
|
-
self.
|
|
102
|
-
self._allocate_samples(Ns)
|
|
153
|
+
# Allocate samples
|
|
154
|
+
self._allocate_samples()
|
|
103
155
|
|
|
104
|
-
#
|
|
105
|
-
|
|
106
|
-
current_samples = self.step_tune(current_samples)
|
|
107
|
-
self._store_samples(self.samples_warmup, current_samples, i)
|
|
108
|
-
self._print_progress(i+1+at_Nb, at_Nb+Nb, 'Warmup')
|
|
156
|
+
# Set targets
|
|
157
|
+
self._set_targets()
|
|
109
158
|
|
|
110
|
-
#
|
|
111
|
-
|
|
112
|
-
current_samples = self.step(current_samples)
|
|
113
|
-
self._store_samples(self.samples, current_samples, i)
|
|
114
|
-
self._print_progress(i+1, at_Ns+Ns, 'Sample')
|
|
159
|
+
# Initialize the samplers
|
|
160
|
+
self._initialize_samplers()
|
|
115
161
|
|
|
116
|
-
#
|
|
117
|
-
|
|
162
|
+
# Validate all targets for samplers.
|
|
163
|
+
self.validate_targets()
|
|
118
164
|
|
|
119
|
-
|
|
120
|
-
|
|
165
|
+
@property
|
|
166
|
+
def scan_order(self):
|
|
167
|
+
if self._scan_order is None:
|
|
168
|
+
return list(self.samplers.keys())
|
|
169
|
+
if self._scan_order == "random":
|
|
170
|
+
arr = list(self.samplers.keys())
|
|
171
|
+
np.random.shuffle(arr) # Shuffle works in-place
|
|
172
|
+
return arr
|
|
173
|
+
return self._scan_order
|
|
121
174
|
|
|
122
|
-
|
|
123
|
-
|
|
175
|
+
# ------------ Public methods ------------
|
|
176
|
+
def validate_targets(self):
|
|
177
|
+
""" Validate each of the conditional targets used in the Gibbs steps """
|
|
178
|
+
if not isinstance(self.target, (JointDistribution, Posterior)):
|
|
179
|
+
raise ValueError('Target distribution must be a JointDistribution or Posterior.')
|
|
180
|
+
for sampler in self.samplers.values():
|
|
181
|
+
sampler.validate_target()
|
|
182
|
+
|
|
183
|
+
def sample(self, Ns) -> 'HybridGibbs':
|
|
184
|
+
""" Sample from the joint distribution using Gibbs sampling
|
|
185
|
+
|
|
186
|
+
Parameters
|
|
187
|
+
----------
|
|
188
|
+
Ns : int
|
|
189
|
+
The number of samples to draw.
|
|
190
|
+
|
|
191
|
+
"""
|
|
192
|
+
for idx in tqdm(range(Ns), "Sample: "):
|
|
193
|
+
|
|
194
|
+
self.step()
|
|
195
|
+
|
|
196
|
+
self._store_samples()
|
|
197
|
+
|
|
198
|
+
# Call callback function if specified
|
|
199
|
+
self._call_callback(idx, Ns)
|
|
200
|
+
|
|
201
|
+
return self
|
|
202
|
+
|
|
203
|
+
def warmup(self, Nb, tune_freq=0.1) -> 'HybridGibbs':
|
|
204
|
+
""" Warmup (tune) the samplers in the Gibbs sampling scheme
|
|
205
|
+
|
|
206
|
+
Parameters
|
|
207
|
+
----------
|
|
208
|
+
Nb : int
|
|
209
|
+
The number of samples to draw during warmup.
|
|
210
|
+
|
|
211
|
+
tune_freq : float, optional
|
|
212
|
+
Frequency of tuning the samplers. Tuning is performed every tune_freq*Nb steps.
|
|
213
|
+
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
tune_interval = max(int(tune_freq * Nb), 1)
|
|
217
|
+
|
|
218
|
+
for idx in tqdm(range(Nb), "Warmup: "):
|
|
219
|
+
|
|
220
|
+
self.step()
|
|
221
|
+
|
|
222
|
+
# Tune the sampler at tuning intervals (matching behavior of Sampler class)
|
|
223
|
+
if (idx + 1) % tune_interval == 0:
|
|
224
|
+
self.tune(tune_interval, idx // tune_interval)
|
|
225
|
+
|
|
226
|
+
self._store_samples()
|
|
227
|
+
|
|
228
|
+
# Call callback function if specified
|
|
229
|
+
self._call_callback(idx, Nb)
|
|
230
|
+
|
|
231
|
+
return self
|
|
232
|
+
|
|
233
|
+
def get_samples(self) -> Dict[str, Samples]:
|
|
234
|
+
samples_object = JointSamples()
|
|
235
|
+
for par_name in self.par_names:
|
|
236
|
+
samples_array = np.array(self.samples[par_name]).T
|
|
237
|
+
samples_object[par_name] = Samples(samples_array, self.target.get_density(par_name).geometry)
|
|
238
|
+
return samples_object
|
|
239
|
+
|
|
240
|
+
def step(self):
|
|
241
|
+
""" Sequentially go through all parameters and sample them conditionally on each other """
|
|
124
242
|
|
|
125
243
|
# Sample from each conditional distribution
|
|
126
|
-
for par_name in
|
|
244
|
+
for par_name in self.scan_order:
|
|
245
|
+
|
|
246
|
+
# Set target for current parameter
|
|
247
|
+
self._set_target(par_name)
|
|
248
|
+
|
|
249
|
+
# Get sampler
|
|
250
|
+
sampler = self.samplers[par_name]
|
|
251
|
+
|
|
252
|
+
# Instead of simply changing the target of the sampler, we reinitialize it.
|
|
253
|
+
# This is to ensure that all internal variables are set to match the new target.
|
|
254
|
+
# To return the sampler to the old state and history, we first extract the state and history
|
|
255
|
+
# before reinitializing the sampler and then set the state and history back to the sampler
|
|
256
|
+
|
|
257
|
+
# Extract state and history from sampler
|
|
258
|
+
sampler_state = sampler.get_state()
|
|
259
|
+
sampler_history = sampler.get_history()
|
|
260
|
+
|
|
261
|
+
# Reinitialize sampler
|
|
262
|
+
sampler.reinitialize()
|
|
263
|
+
|
|
264
|
+
# Set state and history back to sampler
|
|
265
|
+
sampler.set_state(sampler_state)
|
|
266
|
+
sampler.set_history(sampler_history)
|
|
127
267
|
|
|
128
|
-
#
|
|
129
|
-
|
|
268
|
+
# Allow for multiple sampling steps in each Gibbs step
|
|
269
|
+
for _ in range(self.num_sampling_steps[par_name]):
|
|
270
|
+
# Sampling step
|
|
271
|
+
acc = sampler.step()
|
|
130
272
|
|
|
131
|
-
|
|
132
|
-
|
|
273
|
+
# Store acceptance rate in sampler (matching behavior of Sampler class Sample method)
|
|
274
|
+
sampler._acc.append(acc)
|
|
133
275
|
|
|
134
|
-
#
|
|
135
|
-
|
|
276
|
+
# Extract samples (Ensure even 1-dimensional samples are 1D arrays)
|
|
277
|
+
if isinstance(sampler.current_point, np.ndarray):
|
|
278
|
+
self.current_samples[par_name] = sampler.current_point.reshape(-1)
|
|
279
|
+
else:
|
|
280
|
+
self.current_samples[par_name] = sampler.current_point
|
|
281
|
+
|
|
282
|
+
def tune(self, skip_len, update_count):
|
|
283
|
+
""" Run a single tuning step on each of the samplers in the Gibbs sampling scheme
|
|
136
284
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
285
|
+
Parameters
|
|
286
|
+
----------
|
|
287
|
+
skip_len : int
|
|
288
|
+
Defines the number of steps in between tuning (i.e. the tuning interval).
|
|
141
289
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
290
|
+
update_count : int
|
|
291
|
+
The number of times tuning has been performed. Can be used for internal bookkeeping.
|
|
292
|
+
|
|
293
|
+
"""
|
|
294
|
+
for par_name in self.par_names:
|
|
295
|
+
self.samplers[par_name].tune(skip_len=skip_len, update_count=update_count)
|
|
146
296
|
|
|
147
297
|
# ------------ Private methods ------------
|
|
148
|
-
def
|
|
149
|
-
"""
|
|
150
|
-
|
|
151
|
-
|
|
298
|
+
def _call_callback(self, sample_index, num_of_samples):
|
|
299
|
+
""" Calls the callback function. Assumes input is sampler, sample index, and total number of samples """
|
|
300
|
+
if self.callback is not None:
|
|
301
|
+
self.callback(self, sample_index, num_of_samples)
|
|
302
|
+
|
|
303
|
+
def _initialize_samplers(self):
|
|
304
|
+
""" Initialize samplers """
|
|
305
|
+
for sampler in self.samplers.values():
|
|
306
|
+
sampler.initialize()
|
|
307
|
+
|
|
308
|
+
def _initialize_num_sampling_steps(self):
|
|
309
|
+
""" Initialize the number of sampling steps for each sampler. Defaults to 1 if not set by user """
|
|
310
|
+
|
|
311
|
+
if self.num_sampling_steps is None:
|
|
312
|
+
self.num_sampling_steps = {par_name: 1 for par_name in self.par_names}
|
|
313
|
+
|
|
152
314
|
for par_name in self.par_names:
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
# Store samples in self
|
|
156
|
-
if hasattr(self, 'samples'):
|
|
157
|
-
# Append to existing samples (This makes a copy)
|
|
158
|
-
for par_name in self.par_names:
|
|
159
|
-
samples[par_name] = np.hstack((self.samples[par_name], samples[par_name]))
|
|
160
|
-
self.samples = samples
|
|
315
|
+
if par_name not in self.num_sampling_steps:
|
|
316
|
+
self.num_sampling_steps[par_name] = 1
|
|
161
317
|
|
|
162
|
-
def _allocate_samples_warmup(self, Nb):
|
|
163
|
-
""" Allocate memory for samples """
|
|
164
|
-
|
|
165
|
-
# If we already have warmup samples and more are requested raise error
|
|
166
|
-
if hasattr(self, 'samples_warmup') and Nb != 0:
|
|
167
|
-
raise ValueError('Sampler already has run warmup phase. Cannot run warmup phase again.')
|
|
168
318
|
|
|
169
|
-
|
|
319
|
+
def _set_targets(self):
|
|
320
|
+
""" Set targets for all samplers using the current samples """
|
|
321
|
+
par_names = self.par_names
|
|
322
|
+
for par_name in par_names:
|
|
323
|
+
self._set_target(par_name)
|
|
324
|
+
|
|
325
|
+
def _set_target(self, par_name):
|
|
326
|
+
""" Set target conditional distribution for a single parameter using the current samples """
|
|
327
|
+
# Get all other conditional parameters other than the current parameter and update the target
|
|
328
|
+
# This defines - from a joint p(x,y,z) - the conditional distribution p(x|y,z) or p(y|x,z) or p(z|x,y)
|
|
329
|
+
conditional_params = {par_name_: self.current_samples[par_name_] for par_name_ in self.par_names if par_name_ != par_name}
|
|
330
|
+
self.samplers[par_name].target = self.target(**conditional_params)
|
|
331
|
+
|
|
332
|
+
def _allocate_samples(self):
|
|
333
|
+
""" Allocate memory for samples """
|
|
170
334
|
samples = {}
|
|
171
335
|
for par_name in self.par_names:
|
|
172
|
-
samples[par_name] =
|
|
173
|
-
self.
|
|
336
|
+
samples[par_name] = []
|
|
337
|
+
self.samples = samples
|
|
174
338
|
|
|
175
339
|
def _get_initial_points(self):
|
|
176
340
|
""" Get initial points for each parameter """
|
|
177
341
|
initial_points = {}
|
|
178
342
|
for par_name in self.par_names:
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
initial_points[par_name] = self.target.get_density(par_name).init_point
|
|
185
|
-
else:
|
|
186
|
-
initial_points[par_name] = np.ones(self.target.get_density(par_name).dim)
|
|
343
|
+
sampler = self.samplers[par_name]
|
|
344
|
+
if sampler.initial_point is None:
|
|
345
|
+
sampler.initial_point = sampler._get_default_initial_point(self.target.get_density(par_name).dim)
|
|
346
|
+
initial_points[par_name] = sampler.initial_point
|
|
347
|
+
|
|
187
348
|
return initial_points
|
|
188
349
|
|
|
189
|
-
def _store_samples(self
|
|
350
|
+
def _store_samples(self):
|
|
190
351
|
""" Store current samples at index i of samples dict """
|
|
191
352
|
for par_name in self.par_names:
|
|
192
|
-
samples[par_name]
|
|
353
|
+
self.samples[par_name].append(self.current_samples[par_name])
|
|
193
354
|
|
|
194
|
-
def
|
|
195
|
-
"""
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
return samples_object
|
|
200
|
-
|
|
201
|
-
def _print_progress(self, s, Ns, phase):
|
|
202
|
-
"""Prints sampling progress"""
|
|
203
|
-
if Ns < 2: # Don't print progress if only one sample
|
|
204
|
-
return
|
|
205
|
-
if (s % (max(Ns//100,1))) == 0:
|
|
206
|
-
msg = f'{phase} {s} / {Ns}'
|
|
207
|
-
sys.stdout.write('\r'+msg)
|
|
208
|
-
if s==Ns:
|
|
209
|
-
msg = f'{phase} {s} / {Ns}'
|
|
210
|
-
sys.stdout.write('\r'+msg+'\n')
|
|
211
|
-
|
|
212
|
-
# ------------ Private properties ------------
|
|
213
|
-
@property
|
|
214
|
-
def _Ns(self):
|
|
215
|
-
""" Number of samples already taken """
|
|
216
|
-
if hasattr(self, 'samples'):
|
|
217
|
-
return self.samples[self.par_names[0]].shape[-1]
|
|
355
|
+
def __repr__(self):
|
|
356
|
+
""" Return a string representation of the sampler. """
|
|
357
|
+
msg = f"Sampler: {self.__class__.__name__} \n"
|
|
358
|
+
if self.target is None:
|
|
359
|
+
msg += f" Target: None \n"
|
|
218
360
|
else:
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
return self.samples_warmup[self.par_names[0]].shape[-1]
|
|
226
|
-
else:
|
|
227
|
-
return 0
|
|
361
|
+
msg += f" Target: \n \t {self.target} \n\n"
|
|
362
|
+
|
|
363
|
+
for key, value in zip(self.samplers.keys(), self.samplers.values()):
|
|
364
|
+
msg += f" Variable '{key}' with {value} \n"
|
|
365
|
+
|
|
366
|
+
return msg
|