sequince.result
===============

.. py:module:: sequince.result


Attributes
----------

.. autoapisummary::

   sequince.result.NormalizingConstantVarianceMethod


Classes
-------

.. autoapisummary::

   sequince.result.FixedLagLeeWhiteleyDiagnostics
   sequince.result.SMCResult
   sequince.result.MetaSMCResult
   sequince.result.NestedSamplingSMCResult


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

.. py:data:: NormalizingConstantVarianceMethod

.. py:class:: FixedLagLeeWhiteleyDiagnostics

   Diagnostics for a fixed-lag Lee--Whiteley normalizing-constant estimate.

   ``family_ess`` is the inverse concentration of the final normalized
   particle weight carried by each selected-lag ancestor. It lies between one
   and ``distinct_ancestors``; low values indicate genealogical depletion.


   .. py:attribute:: requested_lag
      :type:  int


   .. py:attribute:: traced_resampling_events
      :type:  int


   .. py:attribute:: total_resampling_events
      :type:  int


   .. py:attribute:: distinct_ancestors
      :type:  int


   .. py:attribute:: family_ess
      :type:  float


.. py:class:: SMCResult

   Lightweight container exposing diagnostics for a completed SMC run.


   .. py:attribute:: states
      :type:  collections.abc.Sequence[sequince.state.ParticleState]


   .. py:attribute:: context
      :type:  sequince.steps.context.StepContext


   .. py:attribute:: initial_state
      :type:  sequince.state.ParticleState | None
      :value: None



   .. py:attribute:: outputs
      :type:  collections.abc.Sequence[tuple[Any, ...]]
      :value: ()



   .. py:method:: append_state(state)

      Return a new result with one additional state appended.



   .. py:method:: encode_for_hdf5(*, strict = False)

      Return a portable HDF5 payload for this result.

      By default, unrecognized output dataclasses are converted to
      dictionaries with a warning. ``strict=True`` rejects them instead.



   .. py:method:: save(h5_file_or_group, path = 'result', *, strict = False)

      Save this result below ``path`` in an open HDF5 handle.



   .. py:method:: save_to_file(file_path, path = 'result', *, strict = False)

      Save this result to an HDF5 file without replacing existing data.



   .. py:method:: load_from_file(file_path, path = 'result')
      :classmethod:


      Load a result from an HDF5 file.



   .. py:method:: load(h5_file_or_group, path = 'result')
      :classmethod:


      Load a result from ``path`` in an open HDF5 handle.



   .. py:method:: get_meta_results(key = META_SMC_OUTPUT_KEY)

      Return nested SMC results recorded by meta steps.



   .. py:property:: final_state
      :type: sequince.state.ParticleState


      Return the last state produced by the run.


   .. py:property:: evaluation_counts
      :type: sequince.target.EvaluationCounts


      Return the probabilistic work accumulated during the run.


   .. py:method:: log_normalizing_constant()

      Return the log normalizing constant of the final state.



   .. py:method:: log_evidence()

      Alias for :meth:`log_normalizing_constant` for ordinary SMC runs.

      For NS-SMC, use :meth:`as_nested_sampling_result` for shell evidence.



   .. py:method:: log_normalizing_constant_variance(method = 'incremental', *, lag = None)

      Estimate variance of the final log normalizing-constant estimate.

      ``"incremental"`` sums the per-iteration variance diagnostics. The
      result ignores dependence between SMC iterations.

      ``"lee-whiteley"`` uses the particle genealogy to estimate relative
      normalizing-constant variance, which is also a delta-method estimate of
      log normalizing-constant variance. This estimator requires constant
      particle count and multinomial resampling at every iteration.

      ``"fixed-lag-lee-whiteley"`` This estimator truncates the Lee-Whiteley
      genealogical normalizing-constant variance estimate to the most recent
      ``lag`` resampling events. Particle families are therefore defined by
      their ancestors ``lag`` resampling events before the final population
      rather than by their time-zero ancestors.



   .. py:method:: log_evidence_variance(method = 'incremental', *, lag = None)

      Alias for :meth:`log_normalizing_constant_variance`.



   .. py:method:: fixed_lag_lee_whiteley_diagnostics(lag)

      Return diagnostics for a fixed-lag Lee--Whiteley estimate.



   .. py:method:: log_normalizing_constant_error(method = 'incremental', *, lag = None)

      Return the standard error of the log normalizing constant.



   .. py:method:: log_evidence_error(method = 'incremental', *, lag = None)

      Alias for :meth:`log_normalizing_constant_error`.



   .. py:method:: log_normalizing_constant_history()

      Return the log normalizing-constant trajectory.



   .. py:method:: log_evidence_history()

      Alias for :meth:`log_normalizing_constant_history`.



   .. py:method:: effective_sample_sizes()

      Return the effective sample size (ESS) for every iteration.



   .. py:method:: effective_sample_size_ratios()

      Return ESS / n_particles for each iteration.



   .. py:method:: metadata_history(key, *, default = math.nan)

      Return an array containing a metadata field pulled from each state.



   .. py:method:: summary()

      Return a concise dictionary of high-level diagnostics.



   .. py:method:: as_nested_sampling_result()

      Interpret this run as a likelihood-constrained NS-SMC trajectory.



   .. py:method:: posterior_samples(*, n_samples = None, rng = None, method = 'weights')

      Return samples from the weighted posterior represented by the final state.

      :param n_samples: Number of samples to return. For ``"weights"``, this uniformly
                        down-selects the weighted particle population without replacement.
                        For ``"rejection"``, this is an upper limit on the number of accepted
                        particles. For ``"multinomial"``, exactly this many samples are drawn
                        with replacement. If ``None``, all weighted or rejection-thinned
                        particles are returned, while multinomial sampling draws the same
                        number of samples as there are particles.
      :param rng: Random number generator or seed.
      :param method: Method used to construct the returned posterior representation:

                     - ``"weights"``: return weighted particles, optionally uniformly
                       down-selected without replacement.
                     - ``"rejection"``: independently retain each particle with
                       probability proportional to its weight, returning equal-weight
                       unique samples.
                     - ``"multinomial"``: draw equal-weight samples with replacement
                       according to the particle weights.

      :returns: * *samples* -- Posterior samples. Scalar particles are returned as a column
                  with shape ``(n_samples, 1)``.
                * *sample_weights* -- Normalized weights associated with ``samples``.



   .. py:method:: weighted_mean(*, state_index = -1)

      Return the weighted mean of the specified state (defaults to final).



   .. py:method:: weighted_covariance(*, state_index = -1, ddof = 0)

      Return the weighted covariance matrix for the specified state.



   .. py:method:: apply_weighted(fn, *, state_index = -1)

      Evaluate a function under the weighted empirical distribution.



   .. py:method:: plot_log_normalizing_constant(*, ax = None, label_axes = True, **plot_kwargs)

      Plot the log normalizing-constant trajectory.



   .. py:method:: plot_log_evidence(*, ax = None, label_axes = True, **plot_kwargs)

      Alias for :meth:`plot_log_normalizing_constant`.



   .. py:method:: plot_effective_sample_size(*, normalize = False, ax = None, label_axes = True, **plot_kwargs)

      Plot ESS or the ESS ratio across iterations.



   .. py:method:: plot_metadata_history(key, *, ax = None, default = math.nan, label_axes = True, **plot_kwargs)

      Plot the evolution of a metadata entry stored in each state.



   .. py:method:: plot_corner(*, state_index = -1, include_weights = False, parameter_inds = None, filename = None, **corner_kwargs)

      Plot a corner plot of the particles in the specified state.

      :param state_index: Index of the state to plot (default is -1, the final state).
      :param include_weights: If ``True``, include particle weights in the corner plot.
      :param parameter_inds: Indices of the parameters to include in the corner plot.
                             If ``None`` (default) all parameters are included.
      :param filename: If provided, the plot is saved to this file instead of being returned.
      :param corner_kwargs: Additional keyword arguments passed to the `corner` function.

      :returns: The corner plot figure, if `filename` is not provided.
      :rtype: fig



   .. py:method:: plot_trace(*, ax = None, parameter_inds = None, parameter_labels = None, filename = None, kind = 'violin', **plot_kwargs)

      Plot a trace plot of the particles as a function of state index.

      :param ax: Axis on which to plot.  If ``None``, a new figure and axis are created.
      :param parameter_inds: Indices of the parameters to include in the trace plot.
                             If ``None`` (default) all parameters are included.
      :param parameter_labels: Labels for the parameters to include in the trace plot.
                               If ``None`` (default) generic labels `{x_i}` are used.
      :param filename: If provided, the plot is saved to this file instead of being returned.
      :param kind: The kind of trace plot to create.  Currently only "violin" or "scatter" are supported.
      :param plot_kwargs: Additional keyword arguments passed to the `ax.plot` function.

      :returns: The trace plot axis, if `filename` is not provided.
      :rtype: ax



.. py:class:: MetaSMCResult

   Aggregate results from a SMC run with a meta SMC step.


   .. py:attribute:: results
      :type:  collections.abc.Sequence[SMCResult]


   .. py:method:: encode_for_hdf5(*, strict = False)

      Return the logical HDF5 payload for this meta-SMC result.



   .. py:method:: save(h5_file_or_group, path = 'meta_result', *, strict = False)

      Save this meta-SMC result in an open HDF5 handle.



   .. py:method:: load(h5_file_or_group, path = 'meta_result')
      :classmethod:


      Load a meta-SMC result from an open HDF5 handle.



   .. py:property:: final_result
      :type: SMCResult


      Return the final meta-step result.


   .. py:property:: final_state
      :type: sequince.state.ParticleState


      Return the final particle state from the last meta step.


   .. py:property:: all_states
      :type: list[sequince.state.ParticleState]


      Flatten particle states across all meta steps in execution order.


   .. py:method:: log_normalizing_constant_history()

      Return the log normalizing-constant trajectory across meta steps.



   .. py:method:: log_evidence_history()

      Alias for :meth:`log_normalizing_constant_history`.



   .. py:method:: plot_log_normalizing_constant(*, ax = None, label_axes = True, cmap = 'viridis', **plot_kwargs)

      Plot the log normalizing-constant trajectory across meta steps.



   .. py:method:: plot_log_evidence(*, ax = None, label_axes = True, cmap = 'viridis', **plot_kwargs)

      Alias for :meth:`plot_log_normalizing_constant`.



   .. py:method:: plot_metadata_history(key, *, ax = None, default = math.nan, label_axes = True, cmap = 'viridis', **plot_kwargs)

      Plot metadata history across all meta steps.



   .. py:method:: summary()

      Return a concise dictionary of high-level diagnostics.



.. py:class:: NestedSamplingSMCResult

   Evidence and shell-weighted posterior view of an NS-SMC result.

   The wrapped result's final state is a constrained prior, not a posterior.
   Use this wrapper's posterior_samples method for Bayesian inference.


   .. py:attribute:: result
      :type:  SMCResult


   .. py:property:: states
      :type: collections.abc.Sequence[sequince.state.ParticleState]



   .. py:property:: context
      :type: sequince.steps.context.StepContext



   .. py:property:: final_state
      :type: sequince.state.ParticleState



   .. py:property:: log_evidence
      :type: float


      Accumulated shell evidence, including the live tail if finalized.


   .. py:property:: complete
      :type: bool



   .. py:property:: stop_reason
      :type: str | None


      Readable stopping diagnostic for eager and functional executions.


   .. py:method:: levels()

      Return per-shell diagnostics, including a terminal shell if present.



   .. py:method:: threshold_history()


   .. py:method:: survival_fraction_history()


   .. py:method:: surviving_particles_history()


   .. py:method:: log_prior_volume_history()


   .. py:method:: log_prior_volume_increment_history()


   .. py:method:: log_evidence_history()


   .. py:method:: log_evidence_increment_history()


   .. py:method:: shell_lower_threshold_history()


   .. py:method:: shell_upper_threshold_history()


   .. py:method:: posterior_samples(*, n_samples = None, rng = None, method = 'weights')

      Return shell particles weighted by their contribution to evidence.

      Parameters and return values follow SMCResult.posterior_samples. A
      finalized run with store_shell_particles=True is required. Particle
      weights are quadrature weights; their ESS does not measure MCMC
      independence or account for shared ancestors.



   .. py:method:: summary()


