"""Initializer wrapper that refines the starting mixture with an estimator."""
__author__ = "Danil Totmyanin"
__copyright__ = "Copyright (c) 2026 PySATL project"
__license__ = "SPDX-License-Identifier: MIT"
import inspect
from collections.abc import Callable, Mapping, Sequence
from typing import Any
import numpy as np
from pysatl_core.families import ParametricFamily
from ..core import MixtureModel
from ..estimators import BaseEstimator
from ..typings import UnivariateFloatArray
from .exceptions import InitializationError
from .initializer import Initializer
[документация]
class RefiningInitializer(Initializer):
"""Refines the start of another initializer with a mixture estimator.
The start of ``initializer`` goes to ``estimator.fit(X, start, **fit_kwargs)``. Only the nested initializer gets
the generator.
``fit_kwargs`` is a mapping checked against the signature of ``fit`` at creation, or a function of the families
of the call whose result is checked on every ``initialize``; for example, it can build the ECM parameter groups of
any mixture. The values are not checked.
If the estimator returns fewer components than families (a pruner removed one), the run fails with
:class:`~.InitializationError`, so a multistart skips it.
Parameters
----------
initializer : Initializer
The initializer that builds the starting mixture.
estimator : BaseEstimator
The estimator that refines the start.
fit_kwargs : Mapping[str, Any] | Callable[[Sequence[ParametricFamily]], Mapping[str, Any]] | None, optional
Keyword arguments of every ``fit`` call after the sample and the mixture, or a function that computes them
from the families of each call.
Attributes
----------
initializer : Initializer
The nested initializer, the same object that was passed to the constructor.
estimator : BaseEstimator
The estimator, the same object that was passed to the constructor.
fit_kwargs : dict[str, Any] | Callable[[Sequence[ParametricFamily]], Mapping[str, Any]]
A copy of the passed mapping; the values are shared. A passed function is stored as the same object.
Raises
------
TypeError
If a role has the wrong type, or ``fit_kwargs`` is not a mapping, a callable or None, or a mapping does not
fit the signature of ``fit`` (the error of the signature is the ``__cause__``).
Methods
-------
.. autosummary::
:toctree: generated/
initialize
"""
initializer: Initializer
estimator: BaseEstimator
fit_kwargs: dict[str, Any] | Callable[[Sequence[ParametricFamily]], Mapping[str, Any]]
def __init__(
self,
initializer: Initializer,
estimator: BaseEstimator,
*,
fit_kwargs: Mapping[str, Any] | Callable[[Sequence[ParametricFamily]], Mapping[str, Any]] | None = None,
) -> None:
if not isinstance(initializer, Initializer):
raise TypeError(f"initializer must be an Initializer, got {type(initializer).__name__}.")
if not isinstance(estimator, BaseEstimator):
raise TypeError(f"estimator must be a BaseEstimator, got {type(estimator).__name__}.")
self.initializer = initializer
self.estimator = estimator
if fit_kwargs is None or isinstance(fit_kwargs, Mapping):
self.fit_kwargs = {} if fit_kwargs is None else dict(fit_kwargs)
_check_fit_kwargs(estimator, self.fit_kwargs)
elif callable(fit_kwargs):
self.fit_kwargs = fit_kwargs
else:
raise TypeError(f"fit_kwargs must be a mapping, a callable or None, got {type(fit_kwargs).__name__}.")
def _initialize(
self, X: UnivariateFloatArray, families: Sequence[ParametricFamily], rng: np.random.Generator
) -> MixtureModel:
"""Build the start with the nested initializer and refine it with the estimator.
If ``fit_kwargs`` is a function, it is called with ``tuple(families)`` before the nested initializer builds
the start, and its result is checked against the signature of ``fit``.
Parameters
----------
X : UnivariateFloatArray
The checked sample.
families : Sequence[ParametricFamily]
One family per component of the mixture.
rng : numpy.random.Generator
The generator passed to the nested initializer.
Returns
-------
MixtureModel
The fitted mixture, the same object that ``fit`` returned.
Raises
------
TypeError
If the ``fit_kwargs`` function does not return a mapping, or its result does not fit the signature of
``fit`` (the error of the signature is the ``__cause__``). Errors of the function pass through unchanged.
InitializationError
``"The estimator returned {m} of {k} components."`` if the estimator removed a component.
Errors of the nested initializer and the estimator pass through unchanged.
"""
kwargs: Mapping[str, Any]
if isinstance(self.fit_kwargs, dict):
kwargs = self.fit_kwargs
else:
result: object = self.fit_kwargs(tuple(families))
if not isinstance(result, Mapping):
raise TypeError(f"fit_kwargs must return a mapping, got {type(result).__name__}.")
_check_fit_kwargs(self.estimator, result)
kwargs = result
start = self.initializer.initialize(X, families, random_state=rng)
fitted = self.estimator.fit(X, start, **kwargs)
k = len(families)
if fitted.n_components < k:
raise InitializationError(f"The estimator returned {fitted.n_components} of {k} components.")
return fitted
def _check_fit_kwargs(estimator: BaseEstimator, fit_kwargs: Mapping[Any, Any]) -> None:
"""Check keyword arguments against the signature of the estimator's ``fit``."""
try:
inspect.signature(estimator.fit).bind(None, None, **fit_kwargs)
except TypeError as error:
raise TypeError(f"fit_kwargs do not match the signature of {type(estimator).__name__}.fit: {error}.") from error