Исходный код pysatl_mpest.initializers.cluster.component_estimators.moments_component_estimator

"""Method-of-moments estimation of a component from a cluster.

The method of moments equates the weighted moments of the points of a cluster with the moments of a component
distribution and solves the resulting equations for the free parameters. The weights are a column of the partition
matrix: 1.0 for the points of the cluster and 0.0 for the others.

The formulas live in their own :class:`~pysatl_mpest.core._dispatch.FamilyDispatch` registry keyed by the pair
``(family name, parametrization name)``. The key is built from the family by
:func:`~pysatl_mpest.core._dispatch.family_dispatch_key`, because a component does not exist yet when the initial
mixture is being built, and the registry has no default implementation. The formulas are registered by calling the
function returned by ``register`` instead of using it as a decorator, because ``mutmut`` does not mutate decorated
functions.
"""

__author__ = "Danil Totmyanin"
__copyright__ = "Copyright (c) 2026 PySATL project"
__license__ = "SPDX-License-Identifier: MIT"

from collections.abc import Callable, Mapping

import numpy as np
from pysatl_core.families import ParametricFamily
from pysatl_core.types import FamilyName

from ....core import _components
from ....core._dispatch import FamilyDispatch, family_dispatch_key
from ....typings import UnivariateFloatArray
from .base import ComponentEstimator

type Formula = Callable[[UnivariateFloatArray, UnivariateFloatArray, Mapping[str, float]], dict[str, float]]

_formulas: FamilyDispatch[ParametricFamily, Formula] = FamilyDispatch(family_dispatch_key)


def _normal_mean_std(X: UnivariateFloatArray, h: UnivariateFloatArray, fixed: Mapping[str, float]) -> dict[str, float]:
    r"""Weighted mean and standard deviation; the deviation is taken around the fixed ``mu`` when it is fixed.

    .. math::

        \bar{x} = \frac{\sum_i h_i x_i}{\sum_i h_i}, \qquad
        \sigma = \sqrt{\frac{\sum_i h_i (x_i - m)^2}{\sum_i h_i}},

    where :math:`m` is the fixed ``mu`` when it is fixed and :math:`\bar{x}` otherwise, and
    :math:`\mu = \bar{x}` when ``mu`` is free.

    The variance estimate uses the divisor :math:`n`; compared with the unbiased sample variance it is smaller by
    the factor :math:`(n - 1) / n`, which is immaterial for a starting approximation. A degenerate cluster gives
    ``sigma = 0.0``; this is the correct answer of the formula, not its error. The cluster is not empty.
    """

    free = {}
    if "mu" not in fixed:
        free["mu"] = float(np.average(X, weights=h))
    if "sigma" not in fixed:
        m = fixed["mu"] if "mu" in fixed else free["mu"]
        free["sigma"] = float(np.sqrt(np.average((X - m) ** 2, weights=h)))
    return free


def _exponential_rate(X: UnivariateFloatArray, h: UnivariateFloatArray, fixed: Mapping[str, float]) -> dict[str, float]:
    r"""Inverse weighted mean of the points of the cluster.

    .. math::

        \bar{x} = \frac{\sum_i h_i x_i}{\sum_i h_i}, \qquad
        \lambda = \frac{1}{\bar{x}}.

    ``fixed`` is unused: the single parameter of the family cannot be fixed. The points and the result are not
    checked: points outside the support are used, a negative mean gives a negative rate and a zero mean gives ``inf``;
    the checks of :func:`~pysatl_mpest.initializers.cluster._table._pair.evaluate_pair` reject such values.
    """

    return {"lambda_": float(1.0 / np.average(X, weights=h))}


def _continuous_uniform_standard(
    X: UnivariateFloatArray, h: UnivariateFloatArray, fixed: Mapping[str, float]
) -> dict[str, float]:
    r"""Interval from the weighted mean and standard deviation of the points of the cluster.

    .. math::

        \bar{x} = \frac{\sum_i h_i x_i}{\sum_i h_i}, \qquad
        s = \sqrt{\frac{\sum_i h_i (x_i - \bar{x})^2}{\sum_i h_i}}, \qquad
        a = \bar{x} - \sqrt{3} s, \qquad
        b = \bar{x} + \sqrt{3} s.

    When ``lower_bound`` is fixed to :math:`a`, the estimate is :math:`b = 2\bar{x} - a`; when ``upper_bound`` is
    fixed to :math:`b`, the estimate is :math:`a = 2\bar{x} - b`.

    The variance estimate uses the divisor :math:`n`, so :math:`s^2` is smaller than the unbiased sample variance by
    the factor :math:`(n - 1) / n`; this is immaterial for a starting approximation. The interval may not cover all
    points of the cluster, and then the pair has :math:`\ell = -\infty`. Impossible values, for example an empty
    interval from a fixed bound on the other side of the mean, are returned as they are; the constraint check of
    :func:`~pysatl_mpest.initializers.cluster._table._pair.evaluate_pair` rejects them. The cluster is not empty.
    """

    mean = float(np.average(X, weights=h))
    half_width = float(np.sqrt(3.0)) * float(np.sqrt(np.average((X - mean) ** 2, weights=h)))
    free = {}
    if "lower_bound" not in fixed:
        lower = 2.0 * mean - fixed["upper_bound"] if "upper_bound" in fixed else mean - half_width
        free["lower_bound"] = float(lower)
    if "upper_bound" not in fixed:
        upper = 2.0 * mean - fixed["lower_bound"] if "lower_bound" in fixed else mean + half_width
        free["upper_bound"] = float(upper)
    return free


_formulas.register(FamilyName.NORMAL, "meanStd")(_normal_mean_std)
_formulas.register(FamilyName.EXPONENTIAL, "rate")(_exponential_rate)
_formulas.register(FamilyName.CONTINUOUS_UNIFORM, "standard")(_continuous_uniform_standard)


[документация] class MomentsComponentEstimator(ComponentEstimator): r"""Estimates the free parameters of a component by the method of moments, without optimization. The moments are weighted by a column of the partition matrix: 1.0 for the points of the cluster and 0.0 for the others. The estimator supports ``Normal`` in the ``meanStd`` parametrization, ``Exponential`` in the ``rate`` parametrization and ``ContinuousUniform`` in the ``standard`` parametrization. Parameters fixed through ``family.view(...)`` are taken into account and are not returned. The data are not checked: degenerate values are rejected by the calling code. For ``Normal`` and ``Exponential`` the result coincides with :class:`~.MLEComponentEstimator`. For ``ContinuousUniform`` the interval is centered at the mean of the cluster and its half-width is :math:`\sqrt{3}` times its standard deviation, instead of the minimum and maximum used by :class:`~.MLEComponentEstimator`: the method of moments is less sensitive to outliers, but the interval may not cover the whole cluster. Methods ------- .. autosummary:: :toctree: generated/ supports estimate Examples -------- Pass the estimator to :class:`~pysatl_mpest.initializers.ClusterInitializer` explicitly: .. code-block:: python ClusterInitializer(partitioner, component_estimator=MomentsComponentEstimator()) """
[документация] def supports(self, family: ParametricFamily) -> bool: """Whether a method-of-moments formula is registered for the family and its parametrization. Parameters fixed via ``family.view(...)`` do not affect the answer. Parameters ---------- family : ParametricFamily The family to check. Returns ------- bool Whether :meth:`estimate` accepts the family. """ return _formulas.supports(family)
[документация] def estimate(self, X: UnivariateFloatArray, h: UnivariateFloatArray, family: ParametricFamily) -> dict[str, float]: """Estimate the free parameters of a component of the family by its method-of-moments formula. Parameters ---------- X : UnivariateFloatArray The whole sample. h : UnivariateFloatArray Column of the partition matrix as ``float64``: 1.0 for the points of the cluster and 0.0 for the others; the points of the cluster are ``X[h > 0]``. family : ParametricFamily The family of the component. Returns ------- dict[str, float] Values of the free parameters of the family only. Raises ------ NotImplementedError If no formula is registered for the family and parametrization. Notes ----- The estimator does not raise :class:`~.ComponentEstimationError`: its formulas need no more data than the common lower bound, as many distinct values in the cluster as free parameters, which the calling code checks. """ return _formulas.dispatch(family)(X, h, _components.family_fixed_parameters(family))