sequince.steps.mutation.metropolis
==================================

.. py:module:: sequince.steps.mutation.metropolis


Attributes
----------

.. autoapisummary::

   sequince.steps.mutation.metropolis.logger
   sequince.steps.mutation.metropolis.MutationKernelFactory


Classes
-------

.. autoapisummary::

   sequince.steps.mutation.metropolis.MetropolisHastingsMutation
   sequince.steps.mutation.metropolis.RedBlueMetropolisHastingsMutation
   sequince.steps.mutation.metropolis.DifferentialEvolutionMutation


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

.. py:data:: logger

.. py:data:: MutationKernelFactory

.. py:class:: MetropolisHastingsMutation(log_prob_fn, kernel, *, n_steps = 1, transform = None, transform_refit = 'always', store_chains = False, metrics = ())

   Bases: :py:obj:`sequince.steps.mutation.base.MutationStep`


   Rejuvenate particles with a custom Metropolis-Hastings kernel.

   The kernel operates on the complete particle array, allowing both
   independent and ensemble proposals. All numerical operations remain in the
   input array namespace.


   .. py:method:: apply(state, context, rng)


   .. py:method:: apply_with_mutation_state(state, context, rng, *, n_steps, mutation_state = None)

      Run transitions within a block without finalizing metrics.

      Pass ``mutation_state=None`` to initialize a new block; otherwise pass
      the state returned by the preceding call. The state holds individual
      metric states and cumulative acceptance bookkeeping. It must belong
      to the same metric configuration and mutation coordinate space.

      Returns ``(state, context, output, mutation_state)``. The output's
      metrics remain unset, including on the first and zero-step calls.
      Concrete mutations prepare existing metrics on entry, update state for each
      transition, and return it explicitly without calling metric.result().
      Runtime state must never be stored on the mutation object.

      Use ``apply`` or ``apply_with_n_steps`` for a complete standalone block.
      RepeatedMutationStep uses this method to continue across rounds and
      finalizes metrics once after the complete block.



.. py:class:: RedBlueMetropolisHastingsMutation(log_prob_fn, kernel, *, n_steps = 1, transform = None, transform_refit = 'always', store_chains = False, metrics = ())

   Bases: :py:obj:`MetropolisHastingsMutation`


   Metropolis-Hastings updates using complementary particle ensembles.

   Each of ``n_steps`` is one complete red-blue sweep. The population is
   randomly repartitioned, the red group is updated against the frozen blue
   group, and then blue is updated against the accepted red population. A
   persistent :class:`ComplementaryEnsembleKernel` receives both groups
   directly. DE scale diagnostics are opt-in: configure DEScaleMetrics with
   the kernel's scale_multipliers in metrics, or use AdaptDEScaleWeights,
   which configures the required metric once.


   .. py:method:: initialize_functional_metadata(state, metadata)

      Initialize acceptance metadata before tracing red-blue updates.



   .. py:property:: kernel
      :type: sequince.steps.mutation.kernels.ComplementaryEnsembleKernel


      Fixed complementary kernel; replace between mutation calls.


   .. py:method:: apply(state, context, rng)


   .. py:method:: apply_with_mutation_state(state, context, rng, *, n_steps, mutation_state = None)

      Run transitions within a block without finalizing metrics.

      Pass ``mutation_state=None`` to initialize a new block; otherwise pass
      the state returned by the preceding call. The state holds individual
      metric states and cumulative acceptance bookkeeping. It must belong
      to the same metric configuration and mutation coordinate space.

      Returns ``(state, context, output, mutation_state)``. The output's
      metrics remain unset, including on the first and zero-step calls.
      Concrete mutations prepare existing metrics on entry, update state for each
      transition, and return it explicitly without calling metric.result().
      Runtime state must never be stored on the mutation object.

      Use ``apply`` or ``apply_with_n_steps`` for a complete standalone block.
      RepeatedMutationStep uses this method to continue across rounds and
      finalizes metrics once after the complete block.



.. py:class:: DifferentialEvolutionMutation(log_prob_fn, *, n_steps = 1, gamma = None, gamma_one_probability = 0.1, gamma_randomization = 'none', scale_multipliers = (1.0, ), scale_weights = None, noise_scale = 1e-05, transform = None, transform_refit = 'always', store_chains = False, metrics = ())

   Bases: :py:obj:`RedBlueMetropolisHastingsMutation`


   Rejuvenate particles with red-blue differential-evolution proposals.

   :param log_prob_fn: Function returning the target log probability for each particle, or a
                       :class:`~sequince.target.Target` instance.
   :param n_steps: Number of complete red-blue sweeps to perform.
   :param gamma: Base differential-evolution scale. If ``None``, use
                 ``2.38 / sqrt(2 * n_dimensions)``.
   :param gamma_one_probability: Probability, independently for each proposal, of replacing the
                                 ordinary scale with exactly one.
   :param gamma_randomization: Scale strategy. ``"none"`` uses the fixed base scale; ``"bilby"``
                               multiplies it by an independent ``Gamma(shape=4, scale=0.25)`` draw.
   :param scale_multipliers: Positive factors multiplying the ordinary DE scale independently per
                             particle. Explicit unit-scale moves override these factors.
   :type scale_multipliers: tuple of float
   :param scale_weights: Non-negative mixture weights (normalized internally); None is uniform.
                         The kernel is fixed for each call and scale draws are state-independent.
   :type scale_weights: tuple of float or None
   :param noise_scale: Independent Gaussian noise standard deviation in mutation coordinates,
                       either shared or one value per dimension. Must be finite and
                       non-negative. Default is ``1e-5``; zero disables noise and its RNG draws.
                       With a transform, specify the scale in transformed coordinates.
   :type noise_scale: float or tuple of float
   :param transform: Optional coordinate transform applied before mutation.
   :param transform_refit: Transform refitting policy: ``"always"``, ``"per-context"``,
                           ``"once"``, or a callable receiving the particles and step context.
   :param store_chains: Whether to include the particle state after every complete red-blue
                        sweep in the step output.
   :param metrics: Optional diagnostics. For per-scale DE totals, include
                   DEScaleMetrics(scale_multipliers). AdaptDEScaleWeights configures
                   these diagnostics automatically.
   :type metrics: sequence of MutationMetric


   .. py:method:: validate_functional_configuration(config, state, *, max_steps = None)

      Validate the effective capacity supplied by an enclosing adapter.



   .. py:method:: apply_functional(state, context, random_state)

      Apply a functional step to particle step.

      This returns the updated state, context, next random state, and any
      additional outputs.

      This method is intended for use in functional SMC iterations where the
      random state is explicitly threaded through the computation. Pass the
      backend-native state returned by ``orng.RandomGenerator.state()``;
      for JAX this is a PRNG key array. An ORNG wrapper is reconstructed
      internally, and its advanced state is returned to the caller.



   .. py:method:: apply_dynamic_budget(state, context, random_state, *, n_steps, max_steps, mutation_state = None)

      Run complete sweeps with fixed-capacity diagnostics under JAX.

      :param state: Initialized particles with shape (n_particles, n_dimensions),
                    floating dtype, and any shape-complete target cache.
      :type state: ParticleState
      :param context: Initialized acceptance and optional functional transform metadata.
      :type context: StepContext
      :param random_state: Backend-native state returned by ``orng.RandomGenerator.state()``,
                           threaded explicitly through executed sweeps. For JAX this is a
                           PRNG key array. Pass the state rather than the ORNG generator
                           object; ORNG wrappers are reconstructed internally for draws.
      :type random_state: object
      :param n_steps: Integer budget in [0, max_steps]. Bounds are a caller precondition;
                      compiled runtime values are not checked.
      :type n_steps: array, shape ()
      :param max_steps: Static non-negative capacity bounding the executed sweep count.
      :type max_steps: int
      :param mutation_state: Continuing block metrics, or None to initialize a new block.
      :type mutation_state: MutationStepState or None

      :returns: * **state** (*ParticleState*) -- Updated original-coordinate particles and target cache.
                * **context** (*StepContext*) -- Updated transform, acceptance metadata and evaluation counters.
                * **random_state** (*object*) -- Advanced backend-native ORNG state, unchanged when the budget is
                  zero. For JAX this is a PRNG key array.
                * **output** (*dict*) -- ``steps`` is the scalar executed count. Only this many leading rows
                  of ``acceptance_by_step`` (max_steps,) and ``acceptance_by_half``
                  (max_steps, 2) are valid. Optional ``chain`` has shape (max_steps,
                  n_particles, n_dimensions) in original coordinates. Unused rows are
                  zero. No chain buffer is allocated when storage is disabled.
                * **mutation_state** (*MutationStepState*) -- Accumulated metrics, independent of padded histories, for the block
                  owner to finalize once. ``output["metrics"]`` remains None.

      .. rubric:: Notes

      Call functional metadata and state/context initialization before JIT.
      One-time initialization may fit transforms and populate target caches.
      Block execution with a zero budget performs no transform preparation,
      target evaluation or RNG draw. Transforms remain fixed per segment.



