sequince.prebuilt_samplers
==========================

.. py:module:: sequince.prebuilt_samplers


Functions
---------

.. autoapisummary::

   sequince.prebuilt_samplers.make_standard_bayesian_smc
   sequince.prebuilt_samplers.make_persistent_bayesian_smc
   sequince.prebuilt_samplers.make_nested_sampling_smc


Module Contents
---------------

.. py:function:: 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)

   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.

   :param log_prior: Callable evaluating the log prior density ``log p(x)``.
   :type log_prior: callable
   :param log_likelihood: Callable evaluating the log likelihood ``log l(x)``.
   :type log_likelihood: callable
   :param log_proposal: Optional callable or proposal object providing ``log q(x)`` when
                        importance sampling proposals are used.
   :type log_proposal: callable or ProposalDistribution or None, optional
   :param target_ess_ratio: 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.
   :type target_ess_ratio: float or callable, optional
   :param max_beta: Final tempering beta; typically ``1.0`` for full posterior.
   :type max_beta: float, optional
   :param min_delta: Minimum beta increment allowed in adaptive tempering.
   :type min_delta: float, optional
   :param max_delta: Optional maximum beta increment allowed in adaptive tempering.
   :type max_delta: float or None, optional
   :param adaptive: Whether to adapt the beta schedule using the target ESS.
   :type adaptive: bool, optional
   :param num_steps: Number of fixed beta steps. Required when ``adaptive=False``.
   :type num_steps: int or None, optional
   :param weighting_criterion: Criterion for adaptive tempering; one of ``"ess"`` (default) or ``"cess"``.
   :type weighting_criterion: {"ess", "cess"}, optional
   :param weighting_kwargs: Extra keyword arguments forwarded to the weighting step constructor.
   :type weighting_kwargs: dict[str, Any] or None, optional
   :param resampling: Resampling strategy to use; one of ``"systematic"``, ``"stratified"``,
                      or ``"multinomial"``.
   :type resampling: {"systematic", "stratified", "multinomial"}, optional
   :param resampling_ess_threshold: ESS ratio threshold triggering resampling. Set to ``None`` to disable
                                    ESS-triggered resampling (useful with ``always_resample=True``).
   :type resampling_ess_threshold: float or None, optional
   :param always_resample: 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"``.
   :type always_resample: bool or None, optional
   :param resample_at_end: 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``.
   :type resample_at_end: bool, optional
   :param resampling_kwargs: Extra keyword arguments forwarded to the resampling step constructor.
   :type resampling_kwargs: dict[str, Any] or None, optional
   :param mutation: Mutation strategy to use. Accepts ``"blackjax"``, ``"emcee"``, ``"eryn"``,
                    ``"metropolis-hastings"``, ``"minipcn"`` (default), ``"none"``, or a
                    pre-built ``SMCStep`` instance.
   :type mutation: str or SMCStep, optional
   :param mutation_n_steps: Number of mutation steps to run per iteration.
   :type mutation_n_steps: int, optional
   :param mutation_kwargs: 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.
   :type mutation_kwargs: dict[str, Any] or None, optional
   :param always_mutate: 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``.
   :type always_mutate: bool or None, optional
   :param particle_transform: Transform applied to particles before mutation. Accepts a string
                              identifier for a prebuilt transform, a ``ParticleTransform`` instance,
                              or ``None`` to skip transformation.
   :type particle_transform: ParticleTransform or str or None, optional
   :param particle_transform_kwargs: Extra keyword arguments forwarded to the particle transform
                                     constructor.
   :type particle_transform_kwargs: dict[str, Any] or None, optional
   :param logging_frequency: Frequency (in SMC iterations) at which to log sampler status.
                             Defaults to 1 (log every iteration). If set to 0, logging is disabled.
   :type logging_frequency: int, optional
   :param auto_normalize: Normalize log weights after every iteration (default ``True``).
   :type auto_normalize: bool, optional
   :param callbacks: Optional (initialised) callbacks to attach to the sampler.
   :type callbacks: sequence of callable or None, optional
   :param checkpoint_writers: Optional checkpoint writers attached to the sampler.
   :type checkpoint_writers: sequence of CheckpointWriter or None, optional

   :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``.


.. py:function:: 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)

   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.


.. py:function:: 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)

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

   :param log_prior: Static vectorized log densities. Initial particles must represent the
                     normalized prior; arbitrary importance proposals are not supported.
   :type log_prior: callable
   :param log_likelihood: Static vectorized log densities. Initial particles must represent the
                          normalized prior; arbitrary importance proposals are not supported.
   :type log_likelihood: callable
   :param threshold_schedule: 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.
   :type threshold_schedule: {"worst"}, sequence of float, callable, or None
   :param threshold_quantile: Fraction to discard, in [0, 1). Overrides the default median; cannot
                              be combined with an explicit threshold_schedule.
   :type threshold_quantile: float or None
   :param threshold_inclusive: Retain particles on the threshold boundary. Adaptive schedules require
                               a strict constraint to guarantee progress.
   :type threshold_inclusive: bool
   :param evidence_tolerance: 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.
   :type evidence_tolerance: float or None
   :param log_likelihood_upper_bound: 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.
   :type log_likelihood_upper_bound: float or None
   :param min_log_prior_volume: Optional negative log prior-volume stopping limit.
   :type min_log_prior_volume: float or None
   :param store_shell_particles: Retain discarded particles for posterior reconstruction. Disable for
                                 evidence-only runs with lower memory use.
   :type store_shell_particles: bool
   :param checkpoint_writers: Writers used by the standard SMC checkpoint machinery.
   :type checkpoint_writers: sequence or 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.

   .. rubric:: 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.


