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
@@ -1,561 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- import os
3
- import numpy as np
4
- import pickle as pkl
5
- import warnings
6
- import cuqi
7
- from cuqi.samples import Samples
8
-
9
- try:
10
- from tqdm import tqdm
11
- except ImportError:
12
- def tqdm(iterable, **kwargs):
13
- warnings.warn("Module mcmc: tqdm not found. Install tqdm to get sampling progress.")
14
- return iterable
15
-
16
- class Sampler(ABC):
17
- """ Abstract base class for all samplers.
18
-
19
- Provides a common interface for all samplers. The interface includes methods for sampling, warmup and getting the samples in an object oriented way.
20
-
21
- 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.
22
-
23
- The sampler maintains sets of state and history keys, which are used for features like checkpointing and resuming sampling.
24
-
25
- 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.
26
-
27
- 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.
28
-
29
- Subclasses should ensure that any new variables that are updated in a Markov Monte Carlo step are added to the state or history keys.
30
-
31
- Saving and loading checkpoints saves and loads the state of the sampler (not the history).
32
-
33
- Batching samples via the batch_size parameter saves the sampler history to disk in batches of the specified size.
34
-
35
- Any other attribute stored as part of the sampler (e.g. target, initial_point) is not supposed to be updated
36
- during sampling and should not be part of the state or history.
37
-
38
- """
39
-
40
- _STATE_KEYS = {'current_point'}
41
- """ Set of keys for the state dictionary. """
42
-
43
- _HISTORY_KEYS = {'_samples', '_acc'}
44
- """ Set of keys for the history dictionary. """
45
-
46
- def __init__(self, target:cuqi.density.Density=None, initial_point=None, callback=None):
47
- """ Initializer for abstract base class for all samplers.
48
-
49
- Any subclassing samplers should simply store input parameters as part of the __init__ method.
50
-
51
- The actual initialization of the sampler should be done in the _initialize method.
52
-
53
- Parameters
54
- ----------
55
- target : cuqi.density.Density
56
- The target density.
57
-
58
- initial_point : array-like, optional
59
- The initial point for the sampler. If not given, the sampler will choose an initial point.
60
-
61
- callback : callable, optional
62
- A function that will be called after each sample is drawn. The function should take two arguments: the sample and the index of the sample.
63
- The sample is a 1D numpy array and the index is an integer. The callback function is useful for monitoring the sampler during sampling.
64
-
65
- """
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
-
116
- """
117
- pass
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
134
-
135
- @property
136
- def geometry(self) -> cuqi.geometry.Geometry:
137
- """ Geometry of the target density. """
138
- return self.target.geometry
139
-
140
- @property
141
- def target(self) -> cuqi.density.Density:
142
- """ Return the target density. """
143
- return self._target
144
-
145
- @target.setter
146
- def target(self, value):
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()
151
-
152
- # ------------ Public methods ------------
153
- def get_samples(self) -> Samples:
154
- """ Return the samples. The internal data-structure for the samples is a dynamic list so this creates a copy. """
155
- return Samples(np.array(self._samples).T, self.target.geometry)
156
-
157
- def reinitialize(self):
158
- """ Re-initialize the sampler. This clears the state and history and initializes the sampler again by setting state and history to their original values. """
159
-
160
- # Loop over state and reset to None
161
- for key in self._STATE_KEYS:
162
- setattr(self, key, None)
163
-
164
- # Loop over history and reset to None
165
- for key in self._HISTORY_KEYS:
166
- setattr(self, key, None)
167
-
168
- self._is_initialized = False
169
-
170
- self.initialize()
171
-
172
- def save_checkpoint(self, path):
173
- """ Save the state of the sampler to a file. """
174
-
175
- self._ensure_initialized()
176
-
177
- state = self.get_state()
178
-
179
- # Convert all CUQIarrays to numpy arrays since CUQIarrays do not get pickled correctly
180
- for key, value in state['state'].items():
181
- if isinstance(value, cuqi.array.CUQIarray):
182
- state['state'][key] = value.to_numpy()
183
-
184
- with open(path, 'wb') as handle:
185
- pkl.dump(state, handle, protocol=pkl.HIGHEST_PROTOCOL)
186
-
187
- def load_checkpoint(self, path):
188
- """ Load the state of the sampler from a file. """
189
-
190
- self._ensure_initialized()
191
-
192
- with open(path, 'rb') as handle:
193
- state = pkl.load(handle)
194
-
195
- self.set_state(state)
196
-
197
- def sample(self, Ns, batch_size=0, sample_path='./CUQI_samples/') -> 'Sampler':
198
- """ Sample Ns samples from the target density.
199
-
200
- Parameters
201
- ----------
202
- Ns : int
203
- The number of samples to draw.
204
-
205
- batch_size : int, optional
206
- 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.
207
-
208
- sample_path : str, optional
209
- The path to save the samples. If not specified, the samples are saved to the current working directory under a folder called 'CUQI_samples'.
210
-
211
- """
212
-
213
- self._ensure_initialized()
214
-
215
- # Initialize batch handler
216
- if batch_size > 0:
217
- batch_handler = _BatchHandler(batch_size, sample_path)
218
-
219
- # Any code that needs to be run before sampling
220
- if hasattr(self, "_pre_sample"): self._pre_sample()
221
-
222
- # Draw samples
223
- for _ in tqdm( range(Ns) ):
224
-
225
- # Perform one step of the sampler
226
- acc = self.step()
227
-
228
- # Store samples
229
- self._acc.append(acc)
230
- self._samples.append(self.current_point)
231
-
232
- # Add sample to batch
233
- if batch_size > 0:
234
- batch_handler.add_sample(self.current_point)
235
-
236
- # Call callback function if specified
237
- self._call_callback(self.current_point, len(self._samples)-1)
238
-
239
- return self
240
-
241
-
242
- def warmup(self, Nb, tune_freq=0.1) -> 'Sampler':
243
- """ Warmup the sampler by drawing Nb samples.
244
-
245
- Parameters
246
- ----------
247
- Nb : int
248
- The number of samples to draw during warmup.
249
-
250
- tune_freq : float, optional
251
- The frequency of tuning. Tuning is performed every tune_freq*Nb samples.
252
-
253
- """
254
-
255
- self._ensure_initialized()
256
-
257
- tune_interval = max(int(tune_freq * Nb), 1)
258
-
259
- # Any code that needs to be run before warmup
260
- if hasattr(self, "_pre_warmup"): self._pre_warmup()
261
-
262
- # Draw warmup samples with tuning
263
- for idx in tqdm(range(Nb)):
264
-
265
- # Perform one step of the sampler
266
- acc = self.step()
267
-
268
- # Tune the sampler at tuning intervals
269
- if (idx + 1) % tune_interval == 0:
270
- self.tune(tune_interval, idx // tune_interval)
271
-
272
- # Store samples
273
- self._acc.append(acc)
274
- self._samples.append(self.current_point)
275
-
276
- # Call callback function if specified
277
- self._call_callback(self.current_point, len(self._samples)-1)
278
-
279
- return self
280
-
281
- def get_state(self) -> dict:
282
- """ Return the state of the sampler.
283
-
284
- The state is used when checkpointing the sampler.
285
-
286
- The state of the sampler is a dictionary with keys 'metadata' and 'state'.
287
- The 'metadata' key contains information about the sampler type.
288
- The 'state' key contains the state of the sampler.
289
-
290
- For example, the state of a "MH" sampler could be:
291
-
292
- state = {
293
- 'metadata': {
294
- 'sampler_type': 'MH'
295
- },
296
- 'state': {
297
- 'current_point': np.array([...]),
298
- 'current_target_logd': -123.45,
299
- 'scale': 1.0,
300
- ...
301
- }
302
- }
303
- """
304
- state = {
305
- 'metadata': {
306
- 'sampler_type': self.__class__.__name__
307
- },
308
- 'state': {
309
- key: getattr(self, key) for key in self._STATE_KEYS
310
- }
311
- }
312
- return state
313
-
314
- def set_state(self, state: dict):
315
- """ Set the state of the sampler.
316
-
317
- The state is used when loading the sampler from a checkpoint.
318
-
319
- The state of the sampler is a dictionary with keys 'metadata' and 'state'.
320
-
321
- For example, the state of a "MH" sampler could be:
322
-
323
- state = {
324
- 'metadata': {
325
- 'sampler_type': 'MH'
326
- },
327
- 'state': {
328
- 'current_point': np.array([...]),
329
- 'current_target_logd': -123.45,
330
- 'scale': 1.0,
331
- ...
332
- }
333
- }
334
- """
335
- if state['metadata']['sampler_type'] != self.__class__.__name__:
336
- raise ValueError(f"Sampler type in state dictionary ({state['metadata']['sampler_type']}) does not match the type of the sampler ({self.__class__.__name__}).")
337
-
338
- for key, value in state['state'].items():
339
- if key in self._STATE_KEYS:
340
- setattr(self, key, value)
341
- else:
342
- raise ValueError(f"Key {key} not recognized in state dictionary of sampler {self.__class__.__name__}.")
343
-
344
- def get_history(self) -> dict:
345
- """ Return the history of the sampler. """
346
- history = {
347
- 'metadata': {
348
- 'sampler_type': self.__class__.__name__
349
- },
350
- 'history': {
351
- key: getattr(self, key) for key in self._HISTORY_KEYS
352
- }
353
- }
354
- return history
355
-
356
- def set_history(self, history: dict):
357
- """ Set the history of the sampler. """
358
- if history['metadata']['sampler_type'] != self.__class__.__name__:
359
- raise ValueError(f"Sampler type in history dictionary ({history['metadata']['sampler_type']}) does not match the type of the sampler ({self.__class__.__name__}).")
360
-
361
- for key, value in history['history'].items():
362
- if key in self._HISTORY_KEYS:
363
- setattr(self, key, value)
364
- else:
365
- raise ValueError(f"Key {key} not recognized in history dictionary of sampler {self.__class__.__name__}.")
366
-
367
- # ------------ Private methods ------------
368
- def _call_callback(self, sample, sample_index):
369
- """ Calls the callback function. Assumes input is sample and sample index"""
370
- if self.callback is not None:
371
- self.callback(sample, sample_index)
372
-
373
- def _validate_initialization(self):
374
- """ Validate the initialization of the sampler by checking all state and history keys are set. """
375
-
376
- for key in self._STATE_KEYS:
377
- if getattr(self, key) is None:
378
- raise ValueError(f"Sampler state key {key} is not set after initialization.")
379
-
380
- for key in self._HISTORY_KEYS:
381
- if getattr(self, key) is None:
382
- raise ValueError(f"Sampler history key {key} is not set after initialization.")
383
-
384
- def _ensure_initialized(self):
385
- """ Ensure the sampler is initialized. If not initialize it. """
386
- if not self._is_initialized:
387
- self.initialize()
388
-
389
- def _get_default_initial_point(self, dim):
390
- """ Return the default initial point for the sampler. Defaults to an array of ones. """
391
- return np.ones(dim)
392
-
393
- def __repr__(self):
394
- """ Return a string representation of the sampler. """
395
- if self.target is None:
396
- return f"Sampler: {self.__class__.__name__} \n Target: None"
397
- self._ensure_initialized()
398
- state = self.get_state()
399
- msg = f" Sampler: \n\t {self.__class__.__name__} \n Target: \n \t {self.target} \n Current state: \n"
400
- # Sort keys alphabetically
401
- keys = sorted(state['state'].keys())
402
- # Put _ in the end
403
- keys = [key for key in keys if key[0] != '_'] + [key for key in keys if key[0] == '_']
404
- for key in keys:
405
- value = state['state'][key]
406
- msg += f"\t {key}: {value} \n"
407
- return msg
408
-
409
- class ProposalBasedSampler(Sampler, ABC):
410
- """ Abstract base class for samplers that use a proposal distribution. """
411
-
412
- _STATE_KEYS = Sampler._STATE_KEYS.union({'current_target_logd', 'scale'})
413
-
414
- def __init__(self, target=None, proposal=None, scale=1, **kwargs):
415
- """ Initializer for abstract base class for samplers that use a proposal distribution.
416
-
417
- Any subclassing samplers should simply store input parameters as part of the __init__ method.
418
-
419
- Initialization of the sampler should be done in the _initialize method.
420
-
421
- See :class:`Sampler` for additional details.
422
-
423
- Parameters
424
- ----------
425
- target : cuqi.density.Density
426
- The target density.
427
-
428
- proposal : cuqi.distribution.Distribution, optional
429
- The proposal distribution. If not specified, the default proposal is used.
430
-
431
- scale : float, optional
432
- The scale parameter for the proposal distribution.
433
-
434
- **kwargs : dict
435
- Additional keyword arguments passed to the :class:`Sampler` initializer.
436
-
437
- """
438
-
439
- super().__init__(target, **kwargs)
440
- self.proposal = proposal
441
- self.initial_scale = scale
442
-
443
- def initialize(self):
444
- """ Initialize the sampler by setting and allocating the state and history before sampling starts. """
445
-
446
- if self._is_initialized:
447
- raise ValueError("Sampler is already initialized.")
448
-
449
- if self.target is None:
450
- raise ValueError("Cannot initialize sampler without a target density.")
451
-
452
- # Default values
453
- if self.initial_point is None:
454
- self.initial_point = self._get_default_initial_point(self.dim)
455
-
456
- if self.proposal is None:
457
- self.proposal = self._default_proposal
458
-
459
- # State variables
460
- self.current_point = self.initial_point
461
- self.scale = self.initial_scale
462
-
463
- self.current_target_logd = self.target.logd(self.current_point)
464
-
465
- # History variables
466
- self._samples = []
467
- self._acc = [ 1 ] # TODO. Check if we need to put 1 here.
468
-
469
- self._initialize() # Subclass specific initialization
470
-
471
- self._validate_initialization()
472
-
473
- self._is_initialized = True
474
-
475
- @abstractmethod
476
- def validate_proposal(self):
477
- """ Validate the proposal distribution. """
478
- pass
479
-
480
- @property
481
- def _default_proposal(self):
482
- """ Return the default proposal distribution. Defaults to a Gaussian distribution with zero mean and unit variance. """
483
- return cuqi.distribution.Gaussian(np.zeros(self.dim), 1)
484
-
485
- @property
486
- def proposal(self):
487
- """ The proposal distribution. """
488
- return self._proposal
489
-
490
- @proposal.setter
491
- def proposal(self, proposal):
492
- """ Set the proposal distribution. """
493
- self._proposal = proposal
494
- if self._proposal is not None:
495
- self.validate_proposal()
496
-
497
-
498
- class _BatchHandler:
499
- """ Utility class to handle batching of samples.
500
-
501
- If a batch size is specified, this class will save samples to disk in batches of the specified size.
502
-
503
- This is useful for very large sample sets that do not fit in memory.
504
-
505
- """
506
-
507
- def __init__(self, batch_size=0, sample_path='./CUQI_samples/'):
508
-
509
- if batch_size < 0:
510
- raise ValueError("Batch size should be a non-negative integer")
511
-
512
- self.sample_path = sample_path
513
- self._batch_size = batch_size
514
- self.current_batch = []
515
- self.num_batches_dumped = 0
516
-
517
- @property
518
- def sample_path(self):
519
- """ The path to save the samples. """
520
- return self._sample_path
521
-
522
- @sample_path.setter
523
- def sample_path(self, value):
524
- if not isinstance(value, str):
525
- raise TypeError("Sample path must be a string.")
526
- normalized_path = value.rstrip('/') + '/'
527
- if not os.path.isdir(normalized_path):
528
- try:
529
- os.makedirs(normalized_path, exist_ok=True)
530
- except Exception as e:
531
- raise ValueError(f"Could not create directory at {normalized_path}: {e}")
532
- self._sample_path = normalized_path
533
-
534
- def add_sample(self, sample):
535
- """ Add a sample to the batch if batching. If the batch is full, flush the batch to disk. """
536
-
537
- if self._batch_size <= 0:
538
- return # Batching not used
539
-
540
- self.current_batch.append(sample)
541
-
542
- if len(self.current_batch) >= self._batch_size:
543
- self.flush()
544
-
545
- def flush(self):
546
- """ Flush the current batch of samples to disk. """
547
-
548
- if not self.current_batch:
549
- return # No samples to flush
550
-
551
- # Save the current batch of samples
552
- batch_samples = np.array(self.current_batch)
553
- file_path = f'{self.sample_path}batch_{self.num_batches_dumped:04d}.npz'
554
- np.savez(file_path, samples=batch_samples, batch_id=self.num_batches_dumped)
555
-
556
- self.num_batches_dumped += 1
557
- self.current_batch = [] # Clear the batch after saving
558
-
559
- def finalize(self):
560
- """ Finalize the batch handler. Flush any remaining samples to disk. """
561
- self.flush()
@@ -1,17 +0,0 @@
1
- import cuqi
2
- import inspect
3
-
4
- def find_valid_samplers(target):
5
- """ Finds all samplers in the cuqi.experimental.mcmc module that accept the provided target. """
6
-
7
- all_samplers = [(name, cls) for name, cls in inspect.getmembers(cuqi.experimental.mcmc, inspect.isclass) if issubclass(cls, cuqi.experimental.mcmc.Sampler)]
8
- valid_samplers = []
9
-
10
- for name, sampler in all_samplers:
11
- try:
12
- sampler(target)
13
- valid_samplers += [name]
14
- except:
15
- pass
16
-
17
- return valid_samplers