sequince.prebuilt_samplers#

Functions#

make_standard_bayesian_smc(log_prior, log_likelihood, *)

Return a SequentialMonteCarlo instance configured with standard SMC steps.

make_persistent_bayesian_smc(log_prior, log_likelihood, *)

Return an SMC runner configured for persistent sampling.

make_nested_sampling_smc(log_prior, log_likelihood, *)

Build a nested-sampling SMC pipeline for a normalized prior.

Module Contents#

sequince.prebuilt_samplers.make_standard_bayesian_smc(log_prior, log_likelihood, *, log_proposal=None, target_ess_ratio=0.7, max_beta=1.0, min_delta=1e-08, max_delta=None, adaptive=True, num_steps=None, weighting_criterion='ess', weighting_kwargs=None, resampling='systematic', resampling_ess_threshold=0.5, always_resample=None, resample_at_end=True, resampling_kwargs=None, mutation='minipcn', mutation_n_steps=5, mutation_kwargs=None, always_mutate=None, particle_transform='affine', particle_transform_kwargs=None, logging_frequency=1, auto_normalize=True, callbacks=None, checkpoint_writers=None)[source]#

Return a SequentialMonteCarlo instance configured with standard SMC steps.

The returned sampler applies adaptive tempering, ESS-triggered resampling, and mutation moves tailored for standard Bayesian inference workflows. A TemperedPosterior instance and a shared context dictionary tracking the current beta are returned alongside the sampler for convenience.

Parameters:
  • log_prior (callable) – Callable evaluating the log prior density log p(x).

  • log_likelihood (callable) – Callable evaluating the log likelihood log l(x).

  • log_proposal (callable or ProposalDistribution or None, optional) – Optional callable or proposal object providing log q(x) when importance sampling proposals are used.

  • target_ess_ratio (float or callable, optional) – Target effective sample size ratio used by adaptive tempering, or a callable of the current beta and optional StepContext that returns the target for each iteration.

  • max_beta (float, optional) – Final tempering beta; typically 1.0 for full posterior.

  • min_delta (float, optional) – Minimum beta increment allowed in adaptive tempering.

  • max_delta (float or None, optional) – Optional maximum beta increment allowed in adaptive tempering.

  • adaptive (bool, optional) – Whether to adapt the beta schedule using the target ESS.

  • num_steps (int or None, optional) – Number of fixed beta steps. Required when adaptive=False.

  • weighting_criterion ({"ess", "cess"}, optional) – Criterion for adaptive tempering; one of "ess" (default) or "cess".

  • weighting_kwargs (dict[str, Any] or None, optional) – Extra keyword arguments forwarded to the weighting step constructor.

  • resampling ({"systematic", "stratified", "multinomial"}, optional) – Resampling strategy to use; one of "systematic", "stratified", or "multinomial".

  • resampling_ess_threshold (float or None, optional) – ESS ratio threshold triggering resampling. Set to None to disable ESS-triggered resampling (useful with always_resample=True).

  • always_resample (bool or None, optional) – Force resampling at every iteration regardless of ESS. If set to None, defaults to True if weighting_criterion=="ess" and False if weighting_criterion=="cess".

  • resample_at_end (bool, optional) – If True (default) will always resample when the inverse temperature β reaches 1.0, regardless of ESS. If False, the final resampling may be skipped if always_resample is False and the ESS ratio is above ess_threshold.

  • resampling_kwargs (dict[str, Any] or None, optional) – Extra keyword arguments forwarded to the resampling step constructor.

  • mutation (str or SMCStep, optional) – Mutation strategy to use. Accepts "blackjax", "emcee", "eryn", "metropolis-hastings", "minipcn" (default), "none", or a pre-built SMCStep instance.

  • mutation_n_steps (int, optional) – Number of mutation steps to run per iteration.

  • mutation_kwargs (dict[str, Any] or None, optional) – Extra keyword arguments forwarded to the mutation step constructor. "metropolis-hastings" requires kernel and accepts optional kernel_kwargs. For "emcee", move may be a named move, weighted move configuration, or the "bilby-de" preset. For "blackjax", use algorithm and algorithm_kwargs to configure the JAX mutation kernel.

  • always_mutate (bool or None, optional) – Force mutation at every iteration regardless of resampling. If set to None, defaults to True if always_resample=True and False if always_resample=False.

  • particle_transform (ParticleTransform or str or None, optional) – Transform applied to particles before mutation. Accepts a string identifier for a prebuilt transform, a ParticleTransform instance, or None to skip transformation.

  • particle_transform_kwargs (dict[str, Any] or None, optional) – Extra keyword arguments forwarded to the particle transform constructor.

  • logging_frequency (int, optional) – Frequency (in SMC iterations) at which to log sampler status. Defaults to 1 (log every iteration). If set to 0, logging is disabled.

  • auto_normalize (bool, optional) – Normalize log weights after every iteration (default True).

  • callbacks (sequence of callable or None, optional) – Optional (initialised) callbacks to attach to the sampler.

  • checkpoint_writers (sequence of CheckpointWriter or None, optional) – Optional checkpoint writers attached to the sampler.

Returns:

  • sampler (SequentialMonteCarlo) – Sampler configured with weighting, resampling, and mutation steps.

  • posterior (TemperedPosterior) – Target shared by the sampler’s steps.

  • metadata (dict[str, Any]) – Initial run metadata containing max_beta.

Return type:

Tuple[sequince.smc.SequentialMonteCarlo, sequince.posterior.TemperedPosterior, sequince.typing.MetaData]

sequince.prebuilt_samplers.make_persistent_bayesian_smc(log_prior, log_likelihood, *, log_proposal=None, n_particles=256, target_ess=None, target_total_ess=None, dynamic=False, weighting_kwargs=None, resampling='systematic', resample_at_end=True, resampling_kwargs=None, mutation='minipcn', mutation_n_steps=5, mutation_kwargs=None, particle_transform='affine', particle_transform_kwargs=None, auto_normalize=True, logging_frequency=1, callbacks=None, checkpoint_writers=None)[source]#

Return an SMC runner configured for persistent sampling.

n_particles is the active population size drawn from the complete persistent archive on every iteration. target_ess defaults to twice n_particles. target_ess and target_total_ess are absolute effective sample sizes of that archive; they are not fractions of the active population size.

With dynamic=True, adapt the temperature ESS threshold using the multinomial expected unique fraction (a heuristic under systematic resampling). The initial threshold is truncated to an integer >= 1; target_total_ess never adapts. Updates take effect next iteration.

The initial ParticleState may contain any positive multiple of n_particles equally weighted draws. Its size determines the initial population; the sampler neither draws particles nor chooses this size. Draws must follow log_proposal when configured, otherwise the prior. All initial batches are archived at beta zero on the first call, before tempering and resampling to the fixed active batch size. Nonmultiples are rejected rather than truncated. Initialization is atomic, so checkpoints resume after it, not between initial batches.

A one-batch initial state preserves the existing initialization behavior. The first persistence step prepares evaluations and archives the state at beta zero. With resample_at_end=True (default), selecting beta one always completes resampling and the configured mutation. The next iteration archives that batch and reweights the complete archive before checking termination. If target_total_ess is set, beta-one batches accumulate until the returned weighted archive meets that threshold; no extra batch is generated afterward. The final archive weighting also updates the evidence estimate. With resample_at_end=False, stop immediately after weighting and return the complete weighted archive without generating a final active batch. Progress is logged every logging_frequency iterations and once more for the terminal state. Set logging_frequency=0 to disable it.

For more details see https://arxiv.org/abs/2407.20722.

Parameters:
Return type:

tuple[sequince.smc.SequentialMonteCarlo, sequince.posterior.TemperedPosterior, sequince.typing.MetaData]

sequince.prebuilt_samplers.make_nested_sampling_smc(log_prior, log_likelihood, *, threshold_schedule=None, threshold_quantile=None, threshold_inclusive=False, evidence_tolerance=0.001, log_likelihood_upper_bound=None, store_shell_particles=True, min_log_prior_volume=None, resampling='systematic', resampling_ess_threshold=None, always_resample=True, resampling_kwargs=None, mutation='minipcn', mutation_n_steps=5, mutation_kwargs=None, particle_transform='affine', particle_transform_kwargs=None, logging_frequency=1, auto_normalize=False, callbacks=None, checkpoint_writers=None)[source]#

Build a nested-sampling SMC pipeline for a normalized prior.

Parameters:
  • log_prior (callable) – Static vectorized log densities. Initial particles must represent the normalized prior; arbitrary importance proposals are not supported.

  • log_likelihood (callable) – Static vectorized log densities. Initial particles must represent the normalized prior; arbitrary importance proposals are not supported.

  • threshold_schedule ({"worst"}, sequence of float, callable, or None) – Log-likelihood thresholds. None uses a weighted median. Sequences finalize on exhaustion; callables may raise StopIteration. Callables must implement schedule(log_likelihoods, state, context) -> float. Other user exceptions propagate unchanged.

  • threshold_quantile (float or None) – Fraction to discard, in [0, 1). Overrides the default median; cannot be combined with an explicit threshold_schedule.

  • threshold_inclusive (bool) – Retain particles on the threshold boundary. Adaptive schedules require a strict constraint to guarantee progress.

  • evidence_tolerance (float or None) – Stop when the estimated remaining evidence is this fraction of the accumulated evidence. This is not an upper bound. Set to None to use only fixed-schedule or prior-volume stopping.

  • log_likelihood_upper_bound (float or None) – Known global upper bound on log likelihood. If supplied, evidence stopping uses X * Lmax rather than X * mean(L), protecting against unseen higher-likelihood regions. X remains a Monte Carlo estimate.

  • min_log_prior_volume (float or None) – Optional negative log prior-volume stopping limit.

  • store_shell_particles (bool) – Retain discarded particles for posterior reconstruction. Disable for evidence-only runs with lower memory use.

  • checkpoint_writers (sequence or None) – Writers used by the standard SMC checkpoint machinery.

  • resampling (ResamplingStrategy)

  • resampling_ess_threshold (float | None)

  • always_resample (bool)

  • resampling_kwargs (Dict[str, Any] | None)

  • mutation (sequince.typing.MutationStrategy | sequince.steps.base.SMCStep | None)

  • mutation_n_steps (int)

  • mutation_kwargs (Dict[str, Any] | None)

  • particle_transform (sequince.transforms.ParticleTransform | str | None)

  • particle_transform_kwargs (Dict[str, Any] | None)

  • logging_frequency (int)

  • auto_normalize (bool)

  • callbacks (Sequence[Callable[[sequince.state.ParticleState, sequince.steps.base.StepContext, sequince.result.SMCResult], None]] | None)

Returns:

  • sampler (SequentialMonteCarlo) – Runner using the current step/context APIs. Wrap its result in NestedSamplingSMCResult for evidence and posterior samples. Reaching run(num_steps=…) suspends the run without integrating its live tail; resume it to completion before requesting posterior samples.

  • target (LikelihoodConstrainedPrior) – Mutation target with cached prior and likelihood components.

  • metadata (dict) – Initial runtime bookkeeping.

Return type:

Tuple[sequince.smc.SequentialMonteCarlo, sequince.steps.constraints.LikelihoodConstrainedPrior, sequince.typing.MetaData]

Notes

Other mutation, transformation, resampling, and callback options follow make_standard_bayesian_smc. auto_normalize must be False. State normalizing constants track constrained-prior mass, not Bayesian evidence. The latter is accumulated separately over disjoint shells, including the live tail. Adaptive thresholds do not inherit fixed-schedule unbiasedness guarantees. Likelihood ties are discarded together; sampled plateaus with no survivors are integrated as a terminal shell. This cannot detect unobserved modes.

Functional execution requires JAX arrays, unconditional resampling with unchanged population size, logging_frequency=0, and traceable mutation (BlackJAX or MiniPCN). Use callbacks for host-side logging. Initialize with run_functional or initialize_functional before compiling iterations. Compiled schedules must use backend operations and return a scalar array; positive infinity finalizes the live tail. Python StopIteration is supported by eager and uncompiled schedules, not as a data-dependent compiled branch. Custom target functions and transforms must also be JAX traceable.