Sampler¶
The Sampler class is the main interface to Tempest. It implements the Persistent Sampling algorithm for Bayesian inference.
Overview¶
The sampler manages the entire PS workflow:
- Initialization from prior samples
- Iterative tempering towards the posterior
- MCMC mutation with persistent proposals
- Evidence estimation
Class Reference¶
Sampler ¶
Public API facade for Tempest sampler.
All configuration and algorithm logic is delegated to internal components: - SamplerConfig: validates and stores configuration - SamplerCore: executes the sampling algorithm - StateManager: manages current and historical state
Source code in tempest/sampler.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
__init__ ¶
__init__(prior_transform: callable, log_likelihood: callable, n_dim: int, n_particles: Optional[int] = None, ess_ratio: float = 2.0, volume_variation: Optional[float] = None, log_likelihood_args: Optional[list] = None, log_likelihood_kwargs: Optional[dict] = None, vectorize: bool = False, blobs_dtype: Optional[str] = None, periodic: Optional[list] = None, reflective: Optional[list] = None, pool: Optional[Union[int, object]] = None, clustering: bool = True, normalize: bool = True, cluster_every: int = 1, split_threshold: float = 1.0, n_max_clusters: Optional[int] = None, sample: str = 'tpcn', n_steps: Optional[int] = None, n_max_steps: Optional[int] = None, resample: str = 'mult', output_dir: Optional[str] = None, output_label: Optional[str] = None, random_state: Optional[int] = None)
Initialize Tempest sampler.
Parameters are validated and stored in SamplerConfig, then delegated to SamplerCore for execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior_transform
|
callable
|
Function transforming unit hypercube samples [0,1] to prior parameter space. |
required |
log_likelihood
|
callable
|
Function computing log-likelihood for given parameter values. |
required |
n_dim
|
int
|
Number of dimensions/parameters in the problem. |
required |
n_particles
|
int
|
Number of particles (active samples) per iteration. When None (default), automatically set to 2 * n_dim. |
None
|
ess_ratio
|
float
|
Target ESS ratio (ESS / n_particles) for ESS mode (default: 2.0). The actual target ESS is ess_ratio * n_particles. Used when volume_variation=None. |
2.0
|
volume_variation
|
float
|
Target coefficient of variation for volume to enable dynamic mode (default: None). When None, uses ESS-only mode. When a positive float, uses dynamic mode which searches for beta where volume variation equals this value after finding beta_upper where ESS = n_particles * ess_ratio. This is the CV of sqrt(det(Cov)), measuring the variation of the confidence ellipsoid volume. Lower values enforce more uniform coverage. Must be positive when not None. |
None
|
log_likelihood_args
|
list
|
Positional arguments to pass to log_likelihood function. |
None
|
log_likelihood_kwargs
|
dict
|
Keyword arguments to pass to log_likelihood function. |
None
|
vectorize
|
bool
|
If True, likelihood function accepts batched inputs (n_samples, n_dim). Default is False. |
False
|
blobs_dtype
|
str
|
NumPy dtype string for auxiliary data returned by likelihood. |
None
|
periodic
|
list[int]
|
List of parameter indices with periodic boundary conditions. |
None
|
reflective
|
list[int]
|
List of parameter indices with reflective boundary conditions. |
None
|
pool
|
int or object
|
Parallelization pool. Can be number of processes or Pool object. |
None
|
clustering
|
bool
|
Enable hierarchical Gaussian mixture clustering. Default is True. |
True
|
normalize
|
bool
|
Normalize clusters during training. Default is True. |
True
|
cluster_every
|
int
|
Train clusterer every N iterations. Default is 1. |
1
|
split_threshold
|
float
|
Threshold for splitting clusters. Default is 1.0. |
1.0
|
n_max_clusters
|
int
|
Maximum number of clusters. None means no limit. |
None
|
sample
|
str
|
MCMC proposal method: 'tpcn' or 'rwm'. Default is 'tpcn'. |
'tpcn'
|
n_steps
|
int
|
Base MCMC steps per dimension at optimal acceptance rate of 23.4%. Actual steps adapt as: n_steps_0 * n_dim * (0.234/acceptance_rate) * (sigma_0/sigma)**2. Default is 5. |
None
|
n_max_steps
|
int
|
Maximum MCMC steps per dimension. The actual maximum is n_max_steps * n_dim. Default is 20 × n_steps. |
None
|
resample
|
str
|
Resampling method: 'mult' or 'syst'. Default is 'mult'. |
'mult'
|
output_dir
|
str
|
Output directory for state files. Default is 'states'. |
None
|
output_label
|
str
|
Label prefix for output files. Default is 'ps'. |
None
|
random_state
|
int
|
Random seed for reproducibility. |
None
|
Source code in tempest/sampler.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
run ¶
run(n_total: int = 4096, progress: bool = True, resume_state_path: Union[str, Path, None] = None, save_every: Optional[int] = None)
Run Persistent Sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_total
|
int
|
The total number of effectively independent samples to be
collected (default is |
4096
|
progress
|
bool
|
If True, print progress bar (default is |
True
|
resume_state_path
|
str or Path or None
|
Path of state file used to resume a run. Default is |
None
|
save_every
|
int or None
|
Argument which determines how often (i.e. every how many iterations) |
None
|
Source code in tempest/sampler.py
sample ¶
Perform a single iteration of the PS algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_every
|
int or None
|
Argument which determines how often (i.e. every how many iterations) |
None
|
t0
|
int
|
The starting iteration index, used for determining when to save states.
Default is |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
state |
dict
|
Dictionary containing the current state of the particles. |
Source code in tempest/sampler.py
posterior ¶
posterior(resample: bool = False, return_blobs: bool = False, trim_importance_weights: bool = True, return_logw: bool = False, ess_trim: float = 0.99, bins_trim: int = 1000) -> tuple
Return posterior samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resample
|
bool
|
If True, resample particles (default is |
False
|
return_blobs
|
bool
|
If True, return auxiliary data from likelihood (default is |
False
|
trim_importance_weights
|
bool
|
If True, trim importance weights (default is |
True
|
return_logw
|
bool
|
If True, return log importance weights (default is |
False
|
ess_trim
|
float
|
Effective sample size threshold for trimming (default is |
0.99
|
bins_trim
|
int
|
Number of bins for trimming (default is |
1000
|
Returns:
| Name | Type | Description |
|---|---|---|
x |
ndarray
|
Physical coordinates of posterior samples. |
weights |
ndarray
|
Importance weights. |
logl |
ndarray
|
Log-likelihood values. |
blobs |
ndarray(optional)
|
Auxiliary data if return_blobs=True. |
logw |
ndarray(optional)
|
Log importance weights if return_logw=True. |
Source code in tempest/sampler.py
evidence ¶
Return log evidence estimate and error.
Returns:
| Name | Type | Description |
|---|---|---|
logz |
float
|
Log evidence estimate. |
logz_err |
float or None
|
Error estimate (currently None, for future use). |
Source code in tempest/sampler.py
results ¶
save_state ¶
Save sampler state to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
Path where state will be saved. |
required |
load_state ¶
Load sampler state from file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
Path to state file. |
required |
Quick Reference¶
Creating a Sampler¶
import tempest as tp
import numpy as np
n_dim = 5
def prior_transform(u):
return 20 * u - 10 # U(-10, 10)
def log_likelihood(x):
return -0.5 * np.sum(x**2)
sampler = tp.Sampler(
prior_transform=prior_transform,
log_likelihood=log_likelihood,
n_dim=n_dim,
n_effective=512,
)
Key Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
prior_transform |
callable | - | Prior distribution or transform function |
log_likelihood |
callable | - | Log-likelihood function |
n_dim |
int | - | Number of dimensions |
n_particles |
Optional[int] | None | Number of particles per iteration. None (default) computes as 2 * n_dim. |
ess_ratio |
float | 2.0 | Target ESS ratio (ESS / n_particles). Target ESS = ess_ratio * n_particles. |
volume_variation |
Optional[float] | None | Target coefficient of variation for volume. None for ESS-only mode. |
vectorize |
bool | False | Vectorized likelihood evaluation |
pool |
Pool/int | None | Parallelization pool |
clustering |
bool | True | Enable hierarchical clustering |
Properties¶
| Property | Type | Description |
|---|---|---|
beta |
float | Current inverse temperature |
logz |
float | Current log evidence estimate |
ess |
float | Current effective sample size |
cv |
Optional[float] | Current volume variation (coefficient of variation of sqrt(det(Cov))). None if not yet computed. |
Running the Sampler¶
sampler.run(
n_total=4096, # Target independent samples
progress=True, # Show progress bar
save_every=10, # Checkpoint frequency
)
Extracting Results¶
# Weighted posterior samples
samples, weights, logl = sampler.posterior()
# Evidence estimate
logz, logz_err = sampler.evidence()
# Full results dictionary
results = sampler.results
Examples¶
Basic Usage¶
import numpy as np
import tempest as tp
n_dim = 5
def prior_transform(u):
return 20 * u - 10
def log_likelihood(x):
return -0.5 * np.sum(x**2)
sampler = tp.Sampler(
prior_transform=prior_transform,
log_likelihood=log_likelihood,
n_dim=n_dim,
)
sampler.run(n_total=4096)
samples, weights, logl = sampler.posterior()
With Parallelization¶
sampler = tp.Sampler(
prior_transform=prior_transform,
log_likelihood=log_likelihood,
n_dim=n_dim,
pool=8, # 8 processes
# n_active is optional - automatically set to n_effective // 2 = 256
# For optimal load balancing: n_active=256 (evenly divisible by 8)
)