CUQIpy 1.1.1.post0.dev36__py3-none-any.whl → 1.4.1.post0.dev124__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.

Files changed (92) hide show
  1. cuqi/__init__.py +2 -0
  2. cuqi/_version.py +3 -3
  3. cuqi/algebra/__init__.py +2 -0
  4. cuqi/algebra/_abstract_syntax_tree.py +358 -0
  5. cuqi/algebra/_ordered_set.py +82 -0
  6. cuqi/algebra/_random_variable.py +457 -0
  7. cuqi/array/_array.py +4 -13
  8. cuqi/config.py +7 -0
  9. cuqi/density/_density.py +9 -1
  10. cuqi/distribution/__init__.py +3 -2
  11. cuqi/distribution/_beta.py +7 -11
  12. cuqi/distribution/_cauchy.py +2 -2
  13. cuqi/distribution/_custom.py +0 -6
  14. cuqi/distribution/_distribution.py +31 -45
  15. cuqi/distribution/_gamma.py +7 -3
  16. cuqi/distribution/_gaussian.py +2 -12
  17. cuqi/distribution/_inverse_gamma.py +4 -10
  18. cuqi/distribution/_joint_distribution.py +112 -15
  19. cuqi/distribution/_lognormal.py +0 -7
  20. cuqi/distribution/{_modifiedhalfnormal.py → _modified_half_normal.py} +23 -23
  21. cuqi/distribution/_normal.py +34 -7
  22. cuqi/distribution/_posterior.py +9 -0
  23. cuqi/distribution/_truncated_normal.py +129 -0
  24. cuqi/distribution/_uniform.py +47 -1
  25. cuqi/experimental/__init__.py +2 -2
  26. cuqi/experimental/_recommender.py +216 -0
  27. cuqi/geometry/__init__.py +2 -0
  28. cuqi/geometry/_geometry.py +15 -1
  29. cuqi/geometry/_product_geometry.py +181 -0
  30. cuqi/implicitprior/__init__.py +5 -3
  31. cuqi/implicitprior/_regularized_gaussian.py +483 -0
  32. cuqi/implicitprior/{_regularizedGMRF.py → _regularized_gmrf.py} +4 -2
  33. cuqi/implicitprior/{_regularizedUnboundedUniform.py → _regularized_unbounded_uniform.py} +3 -2
  34. cuqi/implicitprior/_restorator.py +269 -0
  35. cuqi/legacy/__init__.py +2 -0
  36. cuqi/{experimental/mcmc → legacy/sampler}/__init__.py +7 -11
  37. cuqi/legacy/sampler/_conjugate.py +55 -0
  38. cuqi/legacy/sampler/_conjugate_approx.py +52 -0
  39. cuqi/legacy/sampler/_cwmh.py +196 -0
  40. cuqi/legacy/sampler/_gibbs.py +231 -0
  41. cuqi/legacy/sampler/_hmc.py +335 -0
  42. cuqi/{experimental/mcmc → legacy/sampler}/_langevin_algorithm.py +82 -111
  43. cuqi/legacy/sampler/_laplace_approximation.py +184 -0
  44. cuqi/legacy/sampler/_mh.py +190 -0
  45. cuqi/legacy/sampler/_pcn.py +244 -0
  46. cuqi/{experimental/mcmc → legacy/sampler}/_rto.py +132 -90
  47. cuqi/legacy/sampler/_sampler.py +182 -0
  48. cuqi/likelihood/_likelihood.py +9 -1
  49. cuqi/model/__init__.py +1 -1
  50. cuqi/model/_model.py +1361 -359
  51. cuqi/pde/__init__.py +4 -0
  52. cuqi/pde/_observation_map.py +36 -0
  53. cuqi/pde/_pde.py +134 -33
  54. cuqi/problem/_problem.py +93 -87
  55. cuqi/sampler/__init__.py +120 -8
  56. cuqi/sampler/_conjugate.py +376 -35
  57. cuqi/sampler/_conjugate_approx.py +40 -16
  58. cuqi/sampler/_cwmh.py +132 -138
  59. cuqi/{experimental/mcmc → sampler}/_direct.py +1 -1
  60. cuqi/sampler/_gibbs.py +288 -130
  61. cuqi/sampler/_hmc.py +328 -201
  62. cuqi/sampler/_langevin_algorithm.py +284 -100
  63. cuqi/sampler/_laplace_approximation.py +87 -117
  64. cuqi/sampler/_mh.py +47 -157
  65. cuqi/sampler/_pcn.py +65 -213
  66. cuqi/sampler/_rto.py +211 -142
  67. cuqi/sampler/_sampler.py +553 -136
  68. cuqi/samples/__init__.py +1 -1
  69. cuqi/samples/_samples.py +24 -18
  70. cuqi/solver/__init__.py +6 -4
  71. cuqi/solver/_solver.py +230 -26
  72. cuqi/testproblem/_testproblem.py +2 -3
  73. cuqi/utilities/__init__.py +6 -1
  74. cuqi/utilities/_get_python_variable_name.py +2 -2
  75. cuqi/utilities/_utilities.py +182 -2
  76. {CUQIpy-1.1.1.post0.dev36.dist-info → cuqipy-1.4.1.post0.dev124.dist-info}/METADATA +10 -6
  77. cuqipy-1.4.1.post0.dev124.dist-info/RECORD +101 -0
  78. {CUQIpy-1.1.1.post0.dev36.dist-info → cuqipy-1.4.1.post0.dev124.dist-info}/WHEEL +1 -1
  79. CUQIpy-1.1.1.post0.dev36.dist-info/RECORD +0 -92
  80. cuqi/experimental/mcmc/_conjugate.py +0 -197
  81. cuqi/experimental/mcmc/_conjugate_approx.py +0 -81
  82. cuqi/experimental/mcmc/_cwmh.py +0 -191
  83. cuqi/experimental/mcmc/_gibbs.py +0 -268
  84. cuqi/experimental/mcmc/_hmc.py +0 -470
  85. cuqi/experimental/mcmc/_laplace_approximation.py +0 -156
  86. cuqi/experimental/mcmc/_mh.py +0 -78
  87. cuqi/experimental/mcmc/_pcn.py +0 -89
  88. cuqi/experimental/mcmc/_sampler.py +0 -561
  89. cuqi/experimental/mcmc/_utilities.py +0 -17
  90. cuqi/implicitprior/_regularizedGaussian.py +0 -323
  91. {CUQIpy-1.1.1.post0.dev36.dist-info → cuqipy-1.4.1.post0.dev124.dist-info/licenses}/LICENSE +0 -0
  92. {CUQIpy-1.1.1.post0.dev36.dist-info → cuqipy-1.4.1.post0.dev124.dist-info}/top_level.txt +0 -0
cuqi/sampler/_sampler.py CHANGED
@@ -1,177 +1,594 @@
1
1
  from abc import ABC, abstractmethod
2
- import sys
2
+ import os
3
3
  import numpy as np
4
+ import pickle as pkl
5
+ import warnings
4
6
  import cuqi
5
7
  from cuqi.samples import Samples
8
+ from cuqi import config
9
+
10
+ try:
11
+ from tqdm import tqdm
12
+ except ImportError:
13
+ def tqdm(iterable, **kwargs):
14
+ warnings.warn("Module mcmc: tqdm not found. Install tqdm to get sampling progress.")
15
+ return iterable
6
16
 
7
17
  class Sampler(ABC):
18
+ """ Abstract base class for all samplers.
19
+
20
+ Provides a common interface for all samplers. The interface includes methods for sampling, warmup and getting the samples in an object oriented way.
8
21
 
9
- def __init__(self, target, x0=None, dim=None, callback=None):
22
+ Samples are stored in a list to allow for dynamic growth of the sample set. Returning samples is done by creating a new Samples object from the list of samples.
10
23
 
11
- self._dim = dim
12
- if hasattr(target,'dim'):
13
- if self._dim is None:
14
- self._dim = target.dim
15
- elif self._dim != target.dim:
16
- raise ValueError("'dim' need to be None or equal to 'target.dim'")
17
- elif x0 is not None:
18
- self._dim = len(x0)
24
+ The sampler maintains sets of state and history keys, which are used for features like checkpointing and resuming sampling.
19
25
 
20
- self.target = target
26
+ The state of the sampler represents all variables that are updated (replaced) in a Markov Monte Carlo step, e.g. the current point of the sampler.
21
27
 
22
- if x0 is None:
23
- x0 = np.ones(self.dim)
24
- self.x0 = x0
28
+ The history of the sampler represents all variables that are updated (appended) in a Markov Monte Carlo step, e.g. the samples and acceptance rates.
25
29
 
26
- self.callback = callback
30
+ Subclasses should ensure that any new variables that are updated in a Markov Monte Carlo step are added to the state or history keys.
27
31
 
28
- def step(self, x):
29
- """
30
- Perform a single MCMC step
31
- """
32
- # Currently a hack to get step method for any sampler
33
- self.x0 = x
34
- return self.sample(2).samples[:,-1]
32
+ Saving and loading checkpoints saves and loads the state of the sampler (not the history).
35
33
 
36
- def step_tune(self, x, *args, **kwargs):
37
- """
38
- Perform a single MCMC step and tune the sampler. This is used during burn-in.
39
- """
40
- # Currently a hack to get step method for any sampler
41
- out = self.step(x)
42
- self.tune(*args, *kwargs)
43
- return out
34
+ Batching samples via the batch_size parameter saves the sampler history to disk in batches of the specified size.
35
+
36
+ Any other attribute stored as part of the sampler (e.g. target, initial_point) is not supposed to be updated
37
+ during sampling and should not be part of the state or history.
38
+
39
+ """
44
40
 
45
- def tune(self):
41
+ _STATE_KEYS = {'current_point'}
42
+ """ Set of keys for the state dictionary. """
43
+
44
+ _HISTORY_KEYS = {'_samples', '_acc'}
45
+ """ Set of keys for the history dictionary. """
46
+
47
+ def __init__(self, target:cuqi.density.Density=None, initial_point=None, callback=None):
48
+ """ Initializer for abstract base class for all samplers.
49
+
50
+ Any subclassing samplers should simply store input parameters as part of the __init__ method.
51
+
52
+ The actual initialization of the sampler should be done in the _initialize method.
53
+
54
+ Parameters
55
+ ----------
56
+ target : cuqi.density.Density
57
+ The target density.
58
+
59
+ initial_point : array-like, optional
60
+ The initial point for the sampler. If not given, the sampler will choose an initial point.
61
+
62
+ callback : callable, optional
63
+ A function that will be called after each sampling step. It can be useful for monitoring the sampler during sampling.
64
+ 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)`.
46
65
  """
47
- Tune the sampler parameters.
66
+
67
+ self.target = target
68
+ self.initial_point = initial_point
69
+ self.callback = callback
70
+ self._is_initialized = False
71
+
72
+ def initialize(self):
73
+ """ Initialize the sampler by setting and allocating the state and history before sampling starts. """
74
+
75
+ if self._is_initialized:
76
+ raise ValueError("Sampler is already initialized.")
77
+
78
+ if self.target is None:
79
+ raise ValueError("Cannot initialize sampler without a target density.")
80
+
81
+ # Default values
82
+ if self.initial_point is None:
83
+ self.initial_point = self._get_default_initial_point(self.dim)
84
+
85
+ # State variables
86
+ self.current_point = self.initial_point
87
+
88
+ # History variables
89
+ self._samples = []
90
+ self._acc = [ 1 ] # TODO. Check if we need to put 1 here.
91
+
92
+ self._initialize() # Subclass specific initialization
93
+
94
+ self._validate_initialization()
95
+
96
+ self._is_initialized = True
97
+
98
+ # ------------ Abstract methods to be implemented by subclasses ------------
99
+ @abstractmethod
100
+ def step(self):
101
+ """ Perform one step of the sampler by transitioning the current point to a new point according to the sampler's transition kernel. """
102
+ pass
103
+
104
+ @abstractmethod
105
+ def tune(self, skip_len, update_count):
106
+ """ Tune the parameters of the sampler. This method is called after each step of the warmup phase.
107
+
108
+ Parameters
109
+ ----------
110
+ skip_len : int
111
+ Defines the number of steps in between tuning (i.e. the tuning interval).
112
+
113
+ update_count : int
114
+ The number of times tuning has been performed. Can be used for internal bookkeeping.
115
+
48
116
  """
49
117
  pass
50
118
 
119
+ @abstractmethod
120
+ def validate_target(self):
121
+ """ Validate the target is compatible with the sampler. Called when the target is set. Should raise an error if the target is not compatible. """
122
+ pass
123
+
124
+ @abstractmethod
125
+ def _initialize(self):
126
+ """ Subclass specific sampler initialization. Called during the initialization of the sampler which is done before sampling starts. """
127
+ pass
128
+
129
+ # ------------ Public attributes ------------
130
+ @property
131
+ def dim(self) -> int:
132
+ """ Dimension of the target density. """
133
+ return self.target.dim
51
134
 
52
135
  @property
53
- def geometry(self):
54
- if hasattr(self, 'target') and hasattr(self.target, 'geometry'):
55
- geom = self.target.geometry
56
- else:
57
- geom = cuqi.geometry._DefaultGeometry1D(self.dim)
58
- return geom
136
+ def geometry(self) -> cuqi.geometry.Geometry:
137
+ """ Geometry of the target density. """
138
+ return self.target.geometry
59
139
 
60
- @property
61
- def target(self):
62
- return self._target
140
+ @property
141
+ def target(self) -> cuqi.density.Density:
142
+ """ Return the target density. """
143
+ return self._target
63
144
 
64
- @target.setter
145
+ @target.setter
65
146
  def target(self, value):
66
- if not isinstance(value, cuqi.distribution.Distribution) and callable(value):
67
- # obtain self.dim
68
- if self.dim is not None:
69
- dim = self.dim
70
- else:
71
- raise ValueError(f"If 'target' is a lambda function, the parameter 'dim' need to be specified when initializing {self.__class__}.")
147
+ """ Set the target density. Runs validation of the target. """
148
+ self._target = value
149
+ if self._target is not None:
150
+ self.validate_target()
72
151
 
73
- # set target
74
- self._target = cuqi.distribution.UserDefinedDistribution(logpdf_func=value, dim = dim)
152
+ @property
153
+ def current_point(self):
154
+ """ The current point of the sampler. """
155
+ return self._current_point
75
156
 
76
- elif isinstance(value, cuqi.distribution.Distribution):
77
- self._target = value
78
- else:
79
- raise ValueError("'target' need to be either a lambda function or of type 'cuqi.distribution.Distribution'")
157
+ @current_point.setter
158
+ def current_point(self, value):
159
+ """ Set the current point of the sampler. """
160
+ self._current_point = value
80
161
 
162
+ # ------------ Public methods ------------
163
+ def get_samples(self) -> Samples:
164
+ """ Return the samples. The internal data-structure for the samples is a dynamic list so this creates a copy. """
165
+ return Samples(np.array(self._samples).T, self.target.geometry)
81
166
 
82
- @property
83
- def dim(self):
84
- if hasattr(self,'target') and hasattr(self.target,'dim'):
85
- self._dim = self.target.dim
86
- return self._dim
87
-
167
+ def reinitialize(self):
168
+ """ Re-initialize the sampler. This clears the state and history and initializes the sampler again by setting state and history to their original values. """
88
169
 
89
- def sample(self,N,Nb=0):
90
- # Get samples from the samplers sample method
91
- result = self._sample(N,Nb)
92
- return self._create_Sample_object(result,N+Nb)
93
-
94
- def sample_adapt(self,N,Nb=0):
95
- # Get samples from the samplers sample method
96
- result = self._sample_adapt(N,Nb)
97
- return self._create_Sample_object(result,N+Nb)
98
-
99
- def _create_Sample_object(self,result,N):
100
- loglike_eval = None
101
- acc_rate = None
102
- if isinstance(result,tuple):
103
- #Unpack samples+loglike+acc_rate
104
- s = result[0]
105
- if len(result)>1: loglike_eval = result[1]
106
- if len(result)>2: acc_rate = result[2]
107
- if len(result)>3: raise TypeError("Expected tuple of at most 3 elements from sampling method.")
108
- else:
109
- s = result
110
-
111
- #Store samples in cuqi samples object if more than 1 sample
112
- if N==1:
113
- if len(s) == 1 and isinstance(s,np.ndarray): #Extract single value from numpy array
114
- s = s.ravel()[0]
170
+ # Loop over state and reset to None
171
+ for key in self._STATE_KEYS:
172
+ setattr(self, key, None)
173
+
174
+ # Loop over history and reset to None
175
+ for key in self._HISTORY_KEYS:
176
+ setattr(self, key, None)
177
+
178
+ self._is_initialized = False
179
+
180
+ self.initialize()
181
+
182
+ def save_checkpoint(self, path):
183
+ """ Save the state of the sampler to a file. """
184
+
185
+ self._ensure_initialized()
186
+
187
+ state = self.get_state()
188
+
189
+ # Convert all CUQIarrays to numpy arrays since CUQIarrays do not get pickled correctly
190
+ for key, value in state['state'].items():
191
+ if isinstance(value, cuqi.array.CUQIarray):
192
+ state['state'][key] = value.to_numpy()
193
+
194
+ with open(path, 'wb') as handle:
195
+ pkl.dump(state, handle, protocol=pkl.HIGHEST_PROTOCOL)
196
+
197
+ def load_checkpoint(self, path):
198
+ """ Load the state of the sampler from a file. """
199
+
200
+ self._ensure_initialized()
201
+
202
+ with open(path, 'rb') as handle:
203
+ state = pkl.load(handle)
204
+
205
+ self.set_state(state)
206
+
207
+ def sample(self, Ns, Nt=1, batch_size=0, sample_path='./CUQI_samples/') -> 'Sampler':
208
+ """ Sample Ns samples from the target density.
209
+
210
+ Parameters
211
+ ----------
212
+ Ns : int
213
+ The number of samples to draw.
214
+
215
+ Nt : int, optional, default=1
216
+ The thinning interval. If Nt >= 1, every Nt'th sample is stored. The larger Nt, the fewer samples are stored.
217
+
218
+ batch_size : int, optional
219
+ The batch size for saving samples to disk. If 0, no batching is used. If positive, samples are saved to disk in batches of the specified size.
220
+
221
+ sample_path : str, optional
222
+ The path to save the samples. If not specified, the samples are saved to the current working directory under a folder called 'CUQI_samples'.
223
+
224
+ """
225
+ self._ensure_initialized()
226
+
227
+ # Initialize batch handler
228
+ if batch_size > 0:
229
+ batch_handler = _BatchHandler(batch_size, sample_path)
230
+
231
+ # Progress bar printing settings:
232
+ refresh = True if config.PROGRESS_BAR_DYNAMIC_UPDATE else False
233
+ miniters = None if config.PROGRESS_BAR_DYNAMIC_UPDATE else Ns+1
234
+ maxinterval = 10.0 if config.PROGRESS_BAR_DYNAMIC_UPDATE else float("inf")
235
+
236
+ # Draw samples
237
+ pbar = tqdm(range(Ns), "Sample: ", miniters=miniters, maxinterval=maxinterval)
238
+ for idx in pbar:
239
+
240
+ # Perform one step of the sampler
241
+ acc = self.step()
242
+
243
+ # Store samples
244
+ self._acc.append(acc)
245
+ if (Nt > 0) and (idx % Nt == 0):
246
+ self._samples.append(self.current_point)
247
+
248
+ # Display acc rate at progress bar
249
+ pbar.set_postfix_str(f"acc rate: {np.mean(self._acc[-1-idx:]):.2%}",
250
+ refresh=refresh)
251
+
252
+ # Add sample to batch
253
+ if batch_size > 0:
254
+ batch_handler.add_sample(self.current_point)
255
+
256
+ # Call callback function if specified
257
+ self._call_callback(idx, Ns)
258
+
259
+ return self
260
+
261
+ def warmup(self, Nb, Nt=1, tune_freq=0.1) -> 'Sampler':
262
+ """ Warmup the sampler by drawing Nb samples.
263
+
264
+ Parameters
265
+ ----------
266
+ Nb : int
267
+ The number of samples to draw during warmup.
268
+
269
+ Nt : int, optional, default=1
270
+ The thinning interval. If Nt >= 1, every Nt'th sample is stored. The larger Nt, the fewer samples are stored.
271
+
272
+ tune_freq : float, optional
273
+ The frequency of tuning. Tuning is performed every tune_freq*Nb samples.
274
+
275
+ """
276
+
277
+ self._ensure_initialized()
278
+
279
+ tune_interval = max(int(tune_freq * Nb), 1)
280
+
281
+ # Progress bar printing settings:
282
+ refresh = True if config.PROGRESS_BAR_DYNAMIC_UPDATE else False
283
+ miniters = None if config.PROGRESS_BAR_DYNAMIC_UPDATE else Nb+1
284
+ maxinterval = 10.0 if config.PROGRESS_BAR_DYNAMIC_UPDATE else float("inf")
285
+
286
+ # Draw warmup samples with tuning
287
+ pbar = tqdm(range(Nb), "Warmup: ", miniters=miniters, maxinterval=maxinterval)
288
+ for idx in pbar:
289
+
290
+ # Perform one step of the sampler
291
+ acc = self.step()
292
+
293
+ # Tune the sampler at tuning intervals
294
+ if (idx + 1) % tune_interval == 0:
295
+ self.tune(tune_interval, idx // tune_interval)
296
+
297
+ # Store samples
298
+ self._acc.append(acc)
299
+ if (Nt > 0) and (idx % Nt == 0):
300
+ self._samples.append(self.current_point)
301
+
302
+ # Display acc rate at progress bar
303
+ pbar.set_postfix_str(f"acc rate: {np.mean(self._acc[-1-idx:]):.2%}",
304
+ refresh=refresh)
305
+
306
+ # Call callback function if specified
307
+ self._call_callback(idx, Nb)
308
+
309
+ return self
310
+
311
+ def get_state(self) -> dict:
312
+ """ Return the state of the sampler.
313
+
314
+ The state is used when checkpointing the sampler.
315
+
316
+ The state of the sampler is a dictionary with keys 'metadata' and 'state'.
317
+ The 'metadata' key contains information about the sampler type.
318
+ The 'state' key contains the state of the sampler.
319
+
320
+ For example, the state of a "MH" sampler could be:
321
+
322
+ state = {
323
+ 'metadata': {
324
+ 'sampler_type': 'MH'
325
+ },
326
+ 'state': {
327
+ 'current_point': np.array([...]),
328
+ 'current_target_logd': -123.45,
329
+ 'scale': 1.0,
330
+ ...
331
+ }
332
+ }
333
+ """
334
+ state = {
335
+ 'metadata': {
336
+ 'sampler_type': self.__class__.__name__
337
+ },
338
+ 'state': {
339
+ key: getattr(self, key) for key in self._STATE_KEYS
340
+ }
341
+ }
342
+ return state
343
+
344
+ def set_state(self, state: dict):
345
+ """ Set the state of the sampler.
346
+
347
+ The state is used when loading the sampler from a checkpoint.
348
+
349
+ The state of the sampler is a dictionary with keys 'metadata' and 'state'.
350
+
351
+ For example, the state of a "MH" sampler could be:
352
+
353
+ state = {
354
+ 'metadata': {
355
+ 'sampler_type': 'MH'
356
+ },
357
+ 'state': {
358
+ 'current_point': np.array([...]),
359
+ 'current_target_logd': -123.45,
360
+ 'scale': 1.0,
361
+ ...
362
+ }
363
+ }
364
+ """
365
+ if state['metadata']['sampler_type'] != self.__class__.__name__:
366
+ raise ValueError(f"Sampler type in state dictionary ({state['metadata']['sampler_type']}) does not match the type of the sampler ({self.__class__.__name__}).")
367
+
368
+ for key, value in state['state'].items():
369
+ if key in self._STATE_KEYS:
370
+ setattr(self, key, value)
115
371
  else:
116
- s = s.flatten()
117
- else:
118
- s = Samples(s, self.geometry)#, geometry = self.geometry)
119
- s.loglike_eval = loglike_eval
120
- s.acc_rate = acc_rate
121
- return s
372
+ raise ValueError(f"Key {key} not recognized in state dictionary of sampler {self.__class__.__name__}.")
122
373
 
123
- @abstractmethod
124
- def _sample(self,N,Nb):
125
- pass
374
+ def get_history(self) -> dict:
375
+ """ Return the history of the sampler. """
376
+ history = {
377
+ 'metadata': {
378
+ 'sampler_type': self.__class__.__name__
379
+ },
380
+ 'history': {
381
+ key: getattr(self, key) for key in self._HISTORY_KEYS
382
+ }
383
+ }
384
+ return history
126
385
 
127
- @abstractmethod
128
- def _sample_adapt(self,N,Nb):
129
- pass
386
+ def set_history(self, history: dict):
387
+ """ Set the history of the sampler. """
388
+ if history['metadata']['sampler_type'] != self.__class__.__name__:
389
+ raise ValueError(f"Sampler type in history dictionary ({history['metadata']['sampler_type']}) does not match the type of the sampler ({self.__class__.__name__}).")
390
+
391
+ for key, value in history['history'].items():
392
+ if key in self._HISTORY_KEYS:
393
+ setattr(self, key, value)
394
+ else:
395
+ raise ValueError(f"Key {key} not recognized in history dictionary of sampler {self.__class__.__name__}.")
130
396
 
131
- def _print_progress(self,s,Ns):
132
- """Prints sampling progress"""
133
- if Ns > 2:
134
- if (s % (max(Ns//100,1))) == 0:
135
- msg = f'Sample {s} / {Ns}'
136
- sys.stdout.write('\r'+msg)
137
- if s==Ns:
138
- msg = f'Sample {s} / {Ns}'
139
- sys.stdout.write('\r'+msg+'\n')
140
-
141
- def _call_callback(self, sample, sample_index):
142
- """ Calls the callback function. Assumes input is sample and sample index"""
397
+ # ------------ Private methods ------------
398
+ def _call_callback(self, sample_index, num_of_samples):
399
+ """ Calls the callback function. Assumes input is sampler, sample index, and total number of samples """
143
400
  if self.callback is not None:
144
- self.callback(sample, sample_index)
401
+ self.callback(self, sample_index, num_of_samples)
402
+
403
+ def _validate_initialization(self):
404
+ """ Validate the initialization of the sampler by checking all state and history keys are set. """
405
+
406
+ for key in self._STATE_KEYS:
407
+ if getattr(self, key) is None:
408
+ raise ValueError(f"Sampler state key {key} is not set after initialization.")
409
+
410
+ for key in self._HISTORY_KEYS:
411
+ if getattr(self, key) is None:
412
+ raise ValueError(f"Sampler history key {key} is not set after initialization.")
413
+
414
+ def _ensure_initialized(self):
415
+ """ Ensure the sampler is initialized. If not initialize it. """
416
+ if not self._is_initialized:
417
+ self.initialize()
418
+
419
+ def _get_default_initial_point(self, dim):
420
+ """ Return the default initial point for the sampler. Defaults to an array of ones. """
421
+ return np.ones(dim)
422
+
423
+ def __repr__(self):
424
+ """ Return a string representation of the sampler. """
425
+ if self.target is None:
426
+ return f"Sampler: {self.__class__.__name__} \n Target: None"
427
+ else:
428
+ msg = f"Sampler: {self.__class__.__name__} \n Target: \n \t {self.target} "
429
+
430
+ if self._is_initialized:
431
+ state = self.get_state()
432
+ msg += f"\n Current state: \n"
433
+ # Sort keys alphabetically
434
+ keys = sorted(state['state'].keys())
435
+ # Put _ in the end
436
+ keys = [key for key in keys if key[0] != '_'] + [key for key in keys if key[0] == '_']
437
+ for key in keys:
438
+ value = state['state'][key]
439
+ msg += f"\t {key}: {value} \n"
440
+ return msg
441
+
442
+ class ProposalBasedSampler(Sampler, ABC):
443
+ """ Abstract base class for samplers that use a proposal distribution. """
145
444
 
146
- class ProposalBasedSampler(Sampler,ABC):
147
- def __init__(self, target, proposal=None, scale=1, x0=None, dim=None, **kwargs):
148
- #TODO: after fixing None dim
149
- #if dim is None and hasattr(proposal,'dim'):
150
- # dim = proposal.dim
151
- super().__init__(target, x0=x0, dim=dim, **kwargs)
445
+ _STATE_KEYS = Sampler._STATE_KEYS.union({'current_target_logd', 'scale'})
152
446
 
153
- self.proposal =proposal
154
- self.scale = scale
447
+ def __init__(self, target=None, proposal=None, scale=1, **kwargs):
448
+ """ Initializer for abstract base class for samplers that use a proposal distribution.
155
449
 
450
+ Any subclassing samplers should simply store input parameters as part of the __init__ method.
156
451
 
157
- @property
452
+ Initialization of the sampler should be done in the _initialize method.
453
+
454
+ See :class:`Sampler` for additional details.
455
+
456
+ Parameters
457
+ ----------
458
+ target : cuqi.density.Density
459
+ The target density.
460
+
461
+ proposal : cuqi.distribution.Distribution, optional
462
+ The proposal distribution. If not specified, the default proposal is used.
463
+
464
+ scale : float, optional
465
+ The scale parameter for the proposal distribution.
466
+
467
+ **kwargs : dict
468
+ Additional keyword arguments passed to the :class:`Sampler` initializer.
469
+
470
+ """
471
+
472
+ super().__init__(target, **kwargs)
473
+ self.proposal = proposal
474
+ self.initial_scale = scale
475
+
476
+ def initialize(self):
477
+ """ Initialize the sampler by setting and allocating the state and history before sampling starts. """
478
+
479
+ if self._is_initialized:
480
+ raise ValueError("Sampler is already initialized.")
481
+
482
+ if self.target is None:
483
+ raise ValueError("Cannot initialize sampler without a target density.")
484
+
485
+ # Default values
486
+ if self.initial_point is None:
487
+ self.initial_point = self._get_default_initial_point(self.dim)
488
+
489
+ if self.proposal is None:
490
+ self.proposal = self._default_proposal
491
+
492
+ # State variables
493
+ self.current_point = self.initial_point
494
+ self.scale = self.initial_scale
495
+
496
+ self.current_target_logd = self.target.logd(self.current_point)
497
+
498
+ # History variables
499
+ self._samples = []
500
+ self._acc = [ 1 ] # TODO. Check if we need to put 1 here.
501
+
502
+ self._initialize() # Subclass specific initialization
503
+
504
+ self._validate_initialization()
505
+
506
+ self._is_initialized = True
507
+
508
+ @abstractmethod
509
+ def validate_proposal(self):
510
+ """ Validate the proposal distribution. """
511
+ pass
512
+
513
+ @property
514
+ def _default_proposal(self):
515
+ """ Return the default proposal distribution. Defaults to a Gaussian distribution with zero mean and unit variance. """
516
+ return cuqi.distribution.Gaussian(np.zeros(self.dim), 1)
517
+
518
+ @property
158
519
  def proposal(self):
159
- return self._proposal
520
+ """ The proposal distribution. """
521
+ return self._proposal
522
+
523
+ @proposal.setter
524
+ def proposal(self, proposal):
525
+ """ Set the proposal distribution. """
526
+ self._proposal = proposal
527
+ if self._proposal is not None:
528
+ self.validate_proposal()
529
+
160
530
 
161
- @proposal.setter
162
- def proposal(self, value):
163
- self._proposal = value
531
+ class _BatchHandler:
532
+ """ Utility class to handle batching of samples.
533
+
534
+ If a batch size is specified, this class will save samples to disk in batches of the specified size.
535
+
536
+ This is useful for very large sample sets that do not fit in memory.
537
+
538
+ """
539
+
540
+ def __init__(self, batch_size=0, sample_path='./CUQI_samples/'):
541
+
542
+ if batch_size < 0:
543
+ raise ValueError("Batch size should be a non-negative integer")
544
+
545
+ self.sample_path = sample_path
546
+ self._batch_size = batch_size
547
+ self.current_batch = []
548
+ self.num_batches_dumped = 0
164
549
 
165
550
  @property
166
- def geometry(self):
167
- geom1, geom2 = None, None
168
- if hasattr(self, 'proposal') and hasattr(self.proposal, 'geometry') and self.proposal.geometry.par_dim is not None:
169
- geom1= self.proposal.geometry
170
- if hasattr(self, 'target') and hasattr(self.target, 'geometry') and self.target.geometry.par_dim is not None:
171
- geom2 = self.target.geometry
172
- if not isinstance(geom1,cuqi.geometry._DefaultGeometry) and geom1 is not None:
173
- return geom1
174
- elif not isinstance(geom2,cuqi.geometry._DefaultGeometry) and geom2 is not None:
175
- return geom2
176
- else:
177
- return cuqi.geometry._DefaultGeometry1D(self.dim)
551
+ def sample_path(self):
552
+ """ The path to save the samples. """
553
+ return self._sample_path
554
+
555
+ @sample_path.setter
556
+ def sample_path(self, value):
557
+ if not isinstance(value, str):
558
+ raise TypeError("Sample path must be a string.")
559
+ normalized_path = value.rstrip('/') + '/'
560
+ if not os.path.isdir(normalized_path):
561
+ try:
562
+ os.makedirs(normalized_path, exist_ok=True)
563
+ except Exception as e:
564
+ raise ValueError(f"Could not create directory at {normalized_path}: {e}")
565
+ self._sample_path = normalized_path
566
+
567
+ def add_sample(self, sample):
568
+ """ Add a sample to the batch if batching. If the batch is full, flush the batch to disk. """
569
+
570
+ if self._batch_size <= 0:
571
+ return # Batching not used
572
+
573
+ self.current_batch.append(sample)
574
+
575
+ if len(self.current_batch) >= self._batch_size:
576
+ self.flush()
577
+
578
+ def flush(self):
579
+ """ Flush the current batch of samples to disk. """
580
+
581
+ if not self.current_batch:
582
+ return # No samples to flush
583
+
584
+ # Save the current batch of samples
585
+ batch_samples = np.array(self.current_batch)
586
+ file_path = f'{self.sample_path}batch_{self.num_batches_dumped:04d}.npz'
587
+ np.savez(file_path, samples=batch_samples, batch_id=self.num_batches_dumped)
588
+
589
+ self.num_batches_dumped += 1
590
+ self.current_batch = [] # Clear the batch after saving
591
+
592
+ def finalize(self):
593
+ """ Finalize the batch handler. Flush any remaining samples to disk. """
594
+ self.flush()