CUQIpy 1.3.0.post0.dev298__py3-none-any.whl → 1.4.0.post0.dev92__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.
- cuqi/__init__.py +2 -0
- cuqi/_version.py +3 -3
- cuqi/algebra/__init__.py +2 -0
- cuqi/{experimental/algebra/_randomvariable.py → algebra/_random_variable.py} +4 -4
- cuqi/density/_density.py +9 -1
- cuqi/distribution/_distribution.py +25 -16
- cuqi/distribution/_joint_distribution.py +99 -14
- cuqi/distribution/_posterior.py +9 -0
- cuqi/experimental/__init__.py +1 -4
- cuqi/experimental/_recommender.py +4 -4
- cuqi/geometry/__init__.py +2 -0
- cuqi/{experimental/geometry/_productgeometry.py → geometry/_product_geometry.py} +1 -1
- cuqi/implicitprior/__init__.py +1 -1
- cuqi/implicitprior/_restorator.py +35 -1
- 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/likelihood/_likelihood.py +1 -1
- cuqi/model/_model.py +225 -90
- cuqi/pde/__init__.py +4 -0
- cuqi/pde/_observation_map.py +36 -0
- cuqi/pde/_pde.py +52 -21
- 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 +276 -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 +65 -213
- cuqi/sampler/_rto.py +206 -140
- cuqi/sampler/_sampler.py +540 -135
- {cuqipy-1.3.0.post0.dev298.dist-info → cuqipy-1.4.0.post0.dev92.dist-info}/METADATA +1 -1
- cuqipy-1.4.0.post0.dev92.dist-info/RECORD +101 -0
- cuqi/experimental/algebra/__init__.py +0 -2
- cuqi/experimental/geometry/__init__.py +0 -1
- 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 -374
- cuqi/experimental/mcmc/_hmc.py +0 -460
- 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 -306
- cuqi/experimental/mcmc/_sampler.py +0 -564
- cuqipy-1.3.0.post0.dev298.dist-info/RECORD +0 -100
- /cuqi/{experimental/algebra/_ast.py → algebra/_abstract_syntax_tree.py} +0 -0
- /cuqi/{experimental/algebra/_orderedset.py → algebra/_ordered_set.py} +0 -0
- {cuqipy-1.3.0.post0.dev298.dist-info → cuqipy-1.4.0.post0.dev92.dist-info}/WHEEL +0 -0
- {cuqipy-1.3.0.post0.dev298.dist-info → cuqipy-1.4.0.post0.dev92.dist-info}/licenses/LICENSE +0 -0
- {cuqipy-1.3.0.post0.dev298.dist-info → cuqipy-1.4.0.post0.dev92.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,260 @@ 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, Nt=1) -> '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
|
+
Nt : int, optional, default=1
|
|
191
|
+
The thinning interval. If Nt >= 1, every Nt'th sample is stored. The larger Nt, the fewer samples are stored.
|
|
192
|
+
|
|
193
|
+
"""
|
|
194
|
+
for idx in tqdm(range(Ns), "Sample: "):
|
|
124
195
|
|
|
125
|
-
|
|
126
|
-
for par_name in par_names:
|
|
196
|
+
self.step()
|
|
127
197
|
|
|
128
|
-
|
|
129
|
-
|
|
198
|
+
if (Nt > 0) and (idx % Nt == 0):
|
|
199
|
+
self._store_samples()
|
|
130
200
|
|
|
131
|
-
#
|
|
132
|
-
|
|
201
|
+
# Call callback function if specified
|
|
202
|
+
self._call_callback(idx, Ns)
|
|
133
203
|
|
|
134
|
-
|
|
135
|
-
current_samples[par_name] = sampler.step(current_samples[par_name])
|
|
204
|
+
return self
|
|
136
205
|
|
|
137
|
-
|
|
138
|
-
|
|
206
|
+
def warmup(self, Nb, Nt=1, tune_freq=0.1) -> 'HybridGibbs':
|
|
207
|
+
""" Warmup (tune) the samplers in the Gibbs sampling scheme
|
|
208
|
+
|
|
209
|
+
Parameters
|
|
210
|
+
----------
|
|
211
|
+
Nb : int
|
|
212
|
+
The number of samples to draw during warmup.
|
|
139
213
|
|
|
140
|
-
|
|
214
|
+
Nt : int, optional, default=1
|
|
215
|
+
The thinning interval. If Nt >= 1, every Nt'th sample is stored. The larger Nt, the fewer samples are stored.
|
|
216
|
+
|
|
217
|
+
tune_freq : float, optional
|
|
218
|
+
Frequency of tuning the samplers. Tuning is performed every tune_freq*Nb steps.
|
|
219
|
+
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
tune_interval = max(int(tune_freq * Nb), 1)
|
|
223
|
+
|
|
224
|
+
for idx in tqdm(range(Nb), "Warmup: "):
|
|
225
|
+
|
|
226
|
+
self.step()
|
|
227
|
+
|
|
228
|
+
# Tune the sampler at tuning intervals (matching behavior of Sampler class)
|
|
229
|
+
if (idx + 1) % tune_interval == 0:
|
|
230
|
+
self.tune(tune_interval, idx // tune_interval)
|
|
231
|
+
|
|
232
|
+
if (Nt > 0) and (idx % Nt == 0):
|
|
233
|
+
self._store_samples()
|
|
234
|
+
|
|
235
|
+
# Call callback function if specified
|
|
236
|
+
self._call_callback(idx, Nb)
|
|
237
|
+
|
|
238
|
+
return self
|
|
239
|
+
|
|
240
|
+
def get_samples(self) -> Dict[str, Samples]:
|
|
241
|
+
samples_object = JointSamples()
|
|
242
|
+
for par_name in self.par_names:
|
|
243
|
+
samples_array = np.array(self.samples[par_name]).T
|
|
244
|
+
samples_object[par_name] = Samples(samples_array, self.target.get_density(par_name).geometry)
|
|
245
|
+
return samples_object
|
|
246
|
+
|
|
247
|
+
def step(self):
|
|
248
|
+
""" Sequentially go through all parameters and sample them conditionally on each other """
|
|
249
|
+
|
|
250
|
+
# Sample from each conditional distribution
|
|
251
|
+
for par_name in self.scan_order:
|
|
141
252
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
253
|
+
# Set target for current parameter
|
|
254
|
+
self._set_target(par_name)
|
|
255
|
+
|
|
256
|
+
# Get sampler
|
|
257
|
+
sampler = self.samplers[par_name]
|
|
258
|
+
|
|
259
|
+
# Instead of simply changing the target of the sampler, we reinitialize it.
|
|
260
|
+
# This is to ensure that all internal variables are set to match the new target.
|
|
261
|
+
# To return the sampler to the old state and history, we first extract the state and history
|
|
262
|
+
# before reinitializing the sampler and then set the state and history back to the sampler
|
|
263
|
+
|
|
264
|
+
# Extract state and history from sampler
|
|
265
|
+
sampler_state = sampler.get_state()
|
|
266
|
+
sampler_history = sampler.get_history()
|
|
267
|
+
|
|
268
|
+
# Reinitialize sampler
|
|
269
|
+
sampler.reinitialize()
|
|
270
|
+
|
|
271
|
+
# Set state and history back to sampler
|
|
272
|
+
sampler.set_state(sampler_state)
|
|
273
|
+
sampler.set_history(sampler_history)
|
|
274
|
+
|
|
275
|
+
# Allow for multiple sampling steps in each Gibbs step
|
|
276
|
+
for _ in range(self.num_sampling_steps[par_name]):
|
|
277
|
+
# Sampling step
|
|
278
|
+
acc = sampler.step()
|
|
279
|
+
|
|
280
|
+
# Store acceptance rate in sampler (matching behavior of Sampler class Sample method)
|
|
281
|
+
sampler._acc.append(acc)
|
|
282
|
+
|
|
283
|
+
# Extract samples (Ensure even 1-dimensional samples are 1D arrays)
|
|
284
|
+
if isinstance(sampler.current_point, np.ndarray):
|
|
285
|
+
self.current_samples[par_name] = sampler.current_point.reshape(-1)
|
|
286
|
+
else:
|
|
287
|
+
self.current_samples[par_name] = sampler.current_point
|
|
288
|
+
|
|
289
|
+
def tune(self, skip_len, update_count):
|
|
290
|
+
""" Run a single tuning step on each of the samplers in the Gibbs sampling scheme
|
|
291
|
+
|
|
292
|
+
Parameters
|
|
293
|
+
----------
|
|
294
|
+
skip_len : int
|
|
295
|
+
Defines the number of steps in between tuning (i.e. the tuning interval).
|
|
296
|
+
|
|
297
|
+
update_count : int
|
|
298
|
+
The number of times tuning has been performed. Can be used for internal bookkeeping.
|
|
299
|
+
|
|
300
|
+
"""
|
|
301
|
+
for par_name in self.par_names:
|
|
302
|
+
self.samplers[par_name].tune(skip_len=skip_len, update_count=update_count)
|
|
146
303
|
|
|
147
304
|
# ------------ Private methods ------------
|
|
148
|
-
def
|
|
149
|
-
"""
|
|
150
|
-
|
|
151
|
-
|
|
305
|
+
def _call_callback(self, sample_index, num_of_samples):
|
|
306
|
+
""" Calls the callback function. Assumes input is sampler, sample index, and total number of samples """
|
|
307
|
+
if self.callback is not None:
|
|
308
|
+
self.callback(self, sample_index, num_of_samples)
|
|
309
|
+
|
|
310
|
+
def _initialize_samplers(self):
|
|
311
|
+
""" Initialize samplers """
|
|
312
|
+
for sampler in self.samplers.values():
|
|
313
|
+
sampler.initialize()
|
|
314
|
+
|
|
315
|
+
def _initialize_num_sampling_steps(self):
|
|
316
|
+
""" Initialize the number of sampling steps for each sampler. Defaults to 1 if not set by user """
|
|
317
|
+
|
|
318
|
+
if self.num_sampling_steps is None:
|
|
319
|
+
self.num_sampling_steps = {par_name: 1 for par_name in self.par_names}
|
|
320
|
+
|
|
152
321
|
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
|
|
322
|
+
if par_name not in self.num_sampling_steps:
|
|
323
|
+
self.num_sampling_steps[par_name] = 1
|
|
161
324
|
|
|
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
325
|
|
|
169
|
-
|
|
326
|
+
def _set_targets(self):
|
|
327
|
+
""" Set targets for all samplers using the current samples """
|
|
328
|
+
par_names = self.par_names
|
|
329
|
+
for par_name in par_names:
|
|
330
|
+
self._set_target(par_name)
|
|
331
|
+
|
|
332
|
+
def _set_target(self, par_name):
|
|
333
|
+
""" Set target conditional distribution for a single parameter using the current samples """
|
|
334
|
+
# Get all other conditional parameters other than the current parameter and update the target
|
|
335
|
+
# 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)
|
|
336
|
+
conditional_params = {par_name_: self.current_samples[par_name_] for par_name_ in self.par_names if par_name_ != par_name}
|
|
337
|
+
self.samplers[par_name].target = self.target(**conditional_params)
|
|
338
|
+
|
|
339
|
+
def _allocate_samples(self):
|
|
340
|
+
""" Allocate memory for samples """
|
|
170
341
|
samples = {}
|
|
171
342
|
for par_name in self.par_names:
|
|
172
|
-
samples[par_name] =
|
|
173
|
-
self.
|
|
343
|
+
samples[par_name] = []
|
|
344
|
+
self.samples = samples
|
|
174
345
|
|
|
175
346
|
def _get_initial_points(self):
|
|
176
347
|
""" Get initial points for each parameter """
|
|
177
348
|
initial_points = {}
|
|
178
349
|
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)
|
|
350
|
+
sampler = self.samplers[par_name]
|
|
351
|
+
if sampler.initial_point is None:
|
|
352
|
+
sampler.initial_point = sampler._get_default_initial_point(self.target.get_density(par_name).dim)
|
|
353
|
+
initial_points[par_name] = sampler.initial_point
|
|
354
|
+
|
|
187
355
|
return initial_points
|
|
188
356
|
|
|
189
|
-
def _store_samples(self
|
|
357
|
+
def _store_samples(self):
|
|
190
358
|
""" Store current samples at index i of samples dict """
|
|
191
359
|
for par_name in self.par_names:
|
|
192
|
-
samples[par_name]
|
|
360
|
+
self.samples[par_name].append(self.current_samples[par_name])
|
|
193
361
|
|
|
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]
|
|
362
|
+
def __repr__(self):
|
|
363
|
+
""" Return a string representation of the sampler. """
|
|
364
|
+
msg = f"Sampler: {self.__class__.__name__} \n"
|
|
365
|
+
if self.target is None:
|
|
366
|
+
msg += f" Target: None \n"
|
|
218
367
|
else:
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
return self.samples_warmup[self.par_names[0]].shape[-1]
|
|
226
|
-
else:
|
|
227
|
-
return 0
|
|
368
|
+
msg += f" Target: \n \t {self.target} \n\n"
|
|
369
|
+
|
|
370
|
+
for key, value in zip(self.samplers.keys(), self.samplers.values()):
|
|
371
|
+
msg += f" Variable '{key}' with {value} \n"
|
|
372
|
+
|
|
373
|
+
return msg
|