Skip to content

Top-level API

The top-level gmm_divergence namespace is intentionally small. It exposes the classes and functions most users reach for first, plus namespace modules for configuration objects.

What Lives At The Root

Symbol Purpose
Gaussian, GaussianMixture Core Gaussian-family classes
combine_distributions Build a combined Gaussian mixture
kl_divergence, categorical_kl_divergence, symmetric_kl_divergence, jensen_shannon_divergence Main divergence helpers
component_kl_matrix Pairwise component KL diagnostics
aligned_joint_kl_divergence Joint KL for aligned component labels and observations
fit_gaussian_weights, fit_categorical_weights, prune_mixture Main fitting helpers
DivergenceResult, GaussianWeightFitResult, CategoricalWeightFitResult Result containers

What Lives In Namespaces

Configuration and specialized helpers are grouped by namespace:

Namespace Contains
gmm_divergence.divergence Estimator configuration such as MonteCarlo
gmm_divergence.fitting Prepared fits, objectives, optimizers, and candidate selectors
gmm_divergence.sampling Sampling specifications such as Draw and Samples
gmm_divergence.covariance Covariance regularizers and epsilon heuristics
gmm_divergence.distributions Gaussian-family details and combination metadata

Example

import gmm_divergence as gd

p = gd.Gaussian.univariate(mean=0.0, variance=1.0)
q = gd.Gaussian.univariate(mean=1.0, variance=2.0)
estimator = gd.divergence.MonteCarlo(sampling=gd.sampling.Draw(n_samples=50_000, rng=0))
result = gd.kl_divergence(p, q, estimator=estimator)

The sections below document the root exports explicitly. Namespace-only configuration objects are documented on their namespace pages.

Distributions

Gaussian dataclass

Gaussian(
    mean: ArrayLike,
    covariance: ArrayLike,
    *,
    regularizer: CovarianceRegularizer | None = None,
)

Gaussian with mean (n_features,) and positive-definite covariance.

Array-like inputs are copied into read-only float64 arrays. An optional regularizer is applied before validating positive definiteness.

Parameters:

  • mean ((array - like, shape(n_features))) –

    Nonempty, finite feature means.

  • covariance ((array - like, shape(n_features, n_features))) –

    Finite, symmetric covariance. Must be positive definite after any regularization.

  • regularizer (CovarianceRegularizer or None, default: None ) –

    Optional covariance regularization applied before construction.

Source code in src/gmm_divergence/distributions/_gaussian.py
def __init__(
    self,
    mean: npt.ArrayLike,
    covariance: npt.ArrayLike,
    *,
    regularizer: CovarianceRegularizer | None = None,
) -> None:
    mean_array = np.array(mean, dtype=np.float64, copy=True)
    if mean_array.ndim != 1 or mean_array.size == 0:
        msg = "mean must be a nonempty 1D array."
        raise ValueError(msg)
    if not np.isfinite(mean_array).all():
        msg = "mean must contain only finite values."
        raise ValueError(msg)
    if regularizer is not None:
        covariance = regularize_covariance(covariance, regularizer=regularizer)
    covariance_array = as_covariance(covariance, n_features=mean_array.size)
    mean_array.setflags(write=False)
    object.__setattr__(self, "mean", mean_array)
    object.__setattr__(self, "covariance", covariance_array)
    object.__setattr__(self, "_chol", None)
    object.__setattr__(self, "_log_det", None)

n_features property

n_features: int

Number of features in one observation.

cholesky

cholesky() -> FloatArray

Return the cached, read-only lower covariance factor, shape (n_features, n_features).

Source code in src/gmm_divergence/distributions/_gaussian.py
def cholesky(self) -> FloatArray:
    """Return the cached, read-only lower covariance factor, shape (n_features, n_features)."""
    if self._chol is None:
        chol = np.linalg.cholesky(self.covariance).astype(np.float64)
        chol.setflags(write=False)
        object.__setattr__(self, "_chol", chol)
        return chol
    return self._chol

component_arrays

component_arrays() -> tuple[Weights, FloatArray, Covariances]

Return weight, mean, and covariance arrays for one Gaussian component.

Shapes are (1,), (1, n_features), and (1, n_features, n_features).

The weight array is newly allocated; the other arrays are read-only views of this Gaussian's parameters.

Source code in src/gmm_divergence/distributions/_gaussian.py
def component_arrays(self) -> tuple[Weights, FloatArray, Covariances]:
    """Return weight, mean, and covariance arrays for one Gaussian component.

    Shapes are (1,), (1, n_features), and (1, n_features, n_features).

    The weight array is newly allocated; the other arrays are read-only
    views of this Gaussian's parameters.
    """
    return np.array([1.0]), self.mean[None, :], self.covariance[None, :, :]

from_samples classmethod

from_samples(
    samples: ArrayLike, *, regularizer: CovarianceRegularizer | None = None
) -> Gaussian

Estimate a Gaussian from finite observations (n_samples, n_features).

At least two observations are required. Covariance uses the unbiased estimate (divisor n_samples - 1). Singular covariance requires an explicit regularizer.

Parameters:

  • samples ((array - like, shape(n_samples, n_features))) –

    Finite observations with at least two rows and one feature. For one feature, provide a column matrix rather than a 1D vector.

  • regularizer (CovarianceRegularizer or None, default: None ) –

    Optional regularization for the empirical covariance.

Returns:

  • Gaussian –

    Distribution with the sample mean and unbiased sample covariance.

Source code in src/gmm_divergence/distributions/_gaussian.py
@classmethod
def from_samples(
    cls, samples: npt.ArrayLike, *, regularizer: CovarianceRegularizer | None = None
) -> Gaussian:
    """Estimate a Gaussian from finite observations `(n_samples, n_features)`.

    At least two observations are required. Covariance uses the unbiased
    estimate (divisor `n_samples - 1`). Singular covariance requires an
    explicit regularizer.

    Parameters
    ----------
    samples : array-like, shape (n_samples, n_features)
        Finite observations with at least two rows and one feature. For
        one feature, provide a column matrix rather than a 1D vector.
    regularizer : CovarianceRegularizer or None, default=None
        Optional regularization for the empirical covariance.

    Returns
    -------
    Gaussian
        Distribution with the sample mean and unbiased sample covariance.
    """
    observations = np.asarray(samples, dtype=np.float64)
    if observations.ndim != 2 or observations.shape[0] < 2 or observations.shape[1] == 0:
        msg = "samples must have shape (n_samples >= 2, n_features >= 1)."
        raise ValueError(msg)
    if not np.isfinite(observations).all():
        msg = "samples must contain only finite values."
        raise ValueError(msg)
    covariance = np.atleast_2d(np.cov(observations, rowvar=False, bias=False))
    return cls(np.mean(observations, axis=0), covariance, regularizer=regularizer)

isotropic classmethod

isotropic(mean: ArrayLike, *, variance: float = 1.0) -> Gaussian

Create a Gaussian with the same variance along every feature.

Parameters:

  • mean ((array - like, shape(n_features))) –

    Nonempty, finite feature means.

  • variance (float, default: 1.0 ) –

    Finite, strictly positive variance; covariance is variance * I.

Returns:

  • Gaussian –

    Gaussian with independent features and equal marginal variances.

Source code in src/gmm_divergence/distributions/_gaussian.py
@classmethod
def isotropic(cls, mean: npt.ArrayLike, *, variance: float = 1.0) -> Gaussian:
    """Create a Gaussian with the same variance along every feature.

    Parameters
    ----------
    mean : array-like, shape (n_features,)
        Nonempty, finite feature means.
    variance : float, default=1.0
        Finite, strictly positive variance; covariance is `variance * I`.

    Returns
    -------
    Gaussian
        Gaussian with independent features and equal marginal variances.
    """
    _ = validate_positive_finite(variance, name="variance")
    mean_array = np.asarray(mean, dtype=np.float64)
    if mean_array.ndim != 1 or mean_array.size == 0:
        msg = "mean must be a nonempty 1D array."
        raise ValueError(msg)
    return cls(mean_array, np.eye(mean_array.size) * variance)

log_determinant

log_determinant() -> float

Return the cached natural logarithm of the covariance determinant.

Source code in src/gmm_divergence/distributions/_gaussian.py
def log_determinant(self) -> float:
    """Return the cached natural logarithm of the covariance determinant."""
    if self._log_det is None:
        value = float(logdet_from_cholesky(self.cholesky()))
        object.__setattr__(self, "_log_det", value)
        return value
    return self._log_det

logpdf

logpdf(x: ArrayLike) -> FloatArray

Evaluate natural-log densities at one or more points.

Parameters:

  • x ((array - like, shape(n_features) or (n_points, n_features))) –

    Finite observations. A 1D input represents one observation.

Returns:

  • (ndarray, shape(n_points)) –

    Log densities, including a length-one array for a single point.

Source code in src/gmm_divergence/distributions/_gaussian.py
def logpdf(self, x: npt.ArrayLike) -> FloatArray:
    """Evaluate natural-log densities at one or more points.

    Parameters
    ----------
    x : array-like, shape (n_features,) or (n_points, n_features)
        Finite observations. A 1D input represents one observation.

    Returns
    -------
    ndarray, shape (n_points,)
        Log densities, including a length-one array for a single point.
    """
    points = as_points(x, n_features=self.n_features, name="x")
    whitened = np.linalg.solve(self.cholesky(), (points - self.mean).T).T
    return -0.5 * (
        self.n_features * np.log(2 * np.pi)
        + self.log_determinant()
        + np.sum(whitened**2, axis=-1)
    )

pdf

pdf(x: ArrayLike) -> FloatArray

Evaluate densities at one or more points.

Parameters:

  • x ((array - like, shape(n_features) or (n_points, n_features))) –

    Finite observations. A 1D input represents one observation.

Returns:

  • (ndarray, shape(n_points)) –

    Densities, including a length-one array for a single point.

Source code in src/gmm_divergence/distributions/_gaussian.py
def pdf(self, x: npt.ArrayLike) -> FloatArray:
    """Evaluate densities at one or more points.

    Parameters
    ----------
    x : array-like, shape (n_features,) or (n_points, n_features)
        Finite observations. A 1D input represents one observation.

    Returns
    -------
    ndarray, shape (n_points,)
        Densities, including a length-one array for a single point.
    """
    return np.exp(self.logpdf(x))

sample

sample(n_samples: int, *, rng: Generator | int | None = None) -> FloatArray

Draw independent observations from this Gaussian.

Parameters:

  • n_samples (int) –

    Positive number of observations to draw.

  • rng (numpy.random.Generator, int, or None, default: None ) –

    Random source. An integer restarts a reproducible stream on each call; a generator advances its state. None uses fresh entropy.

Returns:

  • (ndarray, shape(n_samples, n_features)) –

    Newly allocated float64 observations.

Source code in src/gmm_divergence/distributions/_gaussian.py
def sample(self, n_samples: int, *, rng: np.random.Generator | int | None = None) -> FloatArray:
    """Draw independent observations from this Gaussian.

    Parameters
    ----------
    n_samples : int
        Positive number of observations to draw.
    rng : numpy.random.Generator, int, or None, default=None
        Random source. An integer restarts a reproducible stream on each
        call; a generator advances its state. None uses fresh entropy.

    Returns
    -------
    ndarray, shape (n_samples, n_features)
        Newly allocated float64 observations.
    """
    n_samples = validate_positive_int(n_samples, name="n_samples")
    return np.random.default_rng(rng).multivariate_normal(
        mean=self.mean, cov=self.covariance, size=n_samples
    )

standard classmethod

standard(n_features: int) -> Gaussian

Create a zero-mean Gaussian with identity covariance.

Parameters:

  • n_features (int) –

    Positive number of features.

Returns:

  • Gaussian –

    Standard multivariate Gaussian of the requested dimension.

Source code in src/gmm_divergence/distributions/_gaussian.py
@classmethod
def standard(cls, n_features: int) -> Gaussian:
    """Create a zero-mean Gaussian with identity covariance.

    Parameters
    ----------
    n_features : int
        Positive number of features.

    Returns
    -------
    Gaussian
        Standard multivariate Gaussian of the requested dimension.
    """
    n_features = validate_positive_int(n_features, name="n_features")
    return cls(np.zeros(n_features), np.eye(n_features))

univariate classmethod

univariate(mean: float = 0.0, variance: float = 1.0) -> Gaussian

Create a one-feature Gaussian from mean and variance.

Parameters:

  • mean (float, default: 0.0 ) –

    Finite feature mean.

  • variance (float, default: 1.0 ) –

    Finite, strictly positive feature variance.

Returns:

  • Gaussian –

    Gaussian with one feature.

Source code in src/gmm_divergence/distributions/_gaussian.py
@classmethod
def univariate(cls, mean: float = 0.0, variance: float = 1.0) -> Gaussian:
    """Create a one-feature Gaussian from mean and variance.

    Parameters
    ----------
    mean : float, default=0.0
        Finite feature mean.
    variance : float, default=1.0
        Finite, strictly positive feature variance.

    Returns
    -------
    Gaussian
        Gaussian with one feature.
    """
    _ = validate_positive_finite(variance, name="variance")
    return cls([mean], [[variance]])

GaussianMixture dataclass

GaussianMixture(
    weights: ArrayLike,
    means: ArrayLike,
    covariances: ArrayLike,
    *,
    regularizer: CovarianceRegularizer | None = None,
    mapping: MixtureMapping | None = None,
)

Immutable mixture of full-covariance Gaussian components.

Parameters:

  • weights ((array - like, shape(n_components))) –

    Finite, nonnegative coefficients with positive total mass. Normalized to sum to one; zero-weight components are retained.

  • means ((array - like, shape(n_components, n_features))) –

    Finite component means, with at least one component and feature.

  • covariances ((array - like, shape(n_components, n_features, n_features))) –

    Finite, symmetric component covariances. Each must be positive definite after any regularization.

  • regularizer (CovarianceRegularizer or None, default: None ) –

    Optional regularization applied to component covariances.

  • mapping (MixtureMapping or None, default: None ) –

    Optional provenance with one row per component.

Notes

Parameter arrays are copied and made read-only. means and covariances describe components; mean and covariance describe the full mixture.

Source code in src/gmm_divergence/distributions/_mixture.py
def __init__(
    self,
    weights: npt.ArrayLike,
    means: npt.ArrayLike,
    covariances: npt.ArrayLike,
    *,
    regularizer: CovarianceRegularizer | None = None,
    mapping: MixtureMapping | None = None,
) -> None:
    means_array = np.array(means, dtype=np.float64, copy=True)
    if means_array.ndim != 2 or 0 in means_array.shape or not np.all(np.isfinite(means_array)):
        msg = "means must be a nonempty finite array of shape (n_components, n_features)."
        raise ValueError(msg)
    weights_array = as_weights(weights, expected_length=means_array.shape[0])
    if regularizer is not None:
        covariances = regularize_covariance(covariances, regularizer=regularizer)
    covariance_array = as_covariances(
        covariances, n_components=means_array.shape[0], n_features=means_array.shape[1]
    )
    if mapping is not None and len(mapping.source_index) != len(weights_array):
        msg = "mapping must contain one row per component."
        raise ValueError(msg)
    means_array.setflags(write=False)
    object.__setattr__(self, "weights", weights_array)
    object.__setattr__(self, "means", means_array)
    object.__setattr__(self, "covariances", covariance_array)
    object.__setattr__(self, "mapping", mapping)
    object.__setattr__(self, "_chol", None)
    object.__setattr__(self, "_log_dets", None)
    object.__setattr__(self, "_aggregate_moments", None)

covariance property

covariance: Covariance

Aggregate covariance, shape (n_features, n_features), read-only.

covariances instance-attribute

covariances: Covariances

Covariance array of shape (n_components, n_features, n_features).

mapping class-attribute instance-attribute

mapping: MixtureMapping | None = None

Optional immediate-source provenance, one row per flattened component.

mean property

mean: FloatArray

Aggregate mean, shape (n_features,), independently owned and read-only.

means instance-attribute

means: FloatArray

Mean array of shape (n_components, n_features).

n_components property

n_components: int

Number of components in the Gaussian mixture.

n_features property

n_features: int

Dimensionality of the Gaussian mixture.

weights instance-attribute

weights: Weights

Weight array of shape (n_components,).

as_gaussian

as_gaussian() -> Gaussian

Convert an exactly single-component mixture to a Gaussian.

Returns:

  • Gaussian –

    Exact distribution with copied component parameters.

Raises:

  • ValueError –

    If the mixture has multiple components. Use moment_match for an approximation in that case.

Source code in src/gmm_divergence/distributions/_mixture.py
def as_gaussian(self) -> Gaussian:
    """Convert an exactly single-component mixture to a Gaussian.

    Returns
    -------
    Gaussian
        Exact distribution with copied component parameters.

    Raises
    ------
    ValueError
        If the mixture has multiple components. Use `moment_match` for an
        approximation in that case.
    """
    if self.n_components != 1:
        msg = (
            "as_gaussian requires exactly one component; use moment_match for an approximation."
        )
        raise ValueError(msg)
    return self.get_component(0)

cholesky

cholesky() -> FloatArray

Return cached, read-only lower factors, shape (n_components, d, d).

Source code in src/gmm_divergence/distributions/_mixture.py
def cholesky(self) -> FloatArray:
    """Return cached, read-only lower factors, shape (n_components, d, d)."""
    if self._chol is not None:
        return self._chol

    cholesky = np.linalg.cholesky(self.covariances).astype(np.float64)
    cholesky.setflags(write=False)
    object.__setattr__(self, "_chol", cholesky)
    return cholesky

component_arrays

component_arrays() -> tuple[Weights, FloatArray, Covariances]

Return read-only weight, mean, and covariance parameter arrays.

Shapes are (n_components,), (n_components, n_features), and (n_components, n_features, n_features). These are the stored arrays, not copies or aggregate moments.

Source code in src/gmm_divergence/distributions/_mixture.py
def component_arrays(self) -> tuple[Weights, FloatArray, Covariances]:
    """Return read-only weight, mean, and covariance parameter arrays.

    Shapes are `(n_components,)`, `(n_components, n_features)`, and
    `(n_components, n_features, n_features)`. These are the stored arrays,
    not copies or aggregate moments.
    """
    return self.weights, self.means, self.covariances

diagnostics

diagnostics() -> MixtureDiagnostics

Summarize component weights and covariance conditioning.

Returns:

  • MixtureDiagnostics –

    Component and feature counts, weight sum and extrema, weight entropy in nats, and independent read-only per-component condition numbers.

Source code in src/gmm_divergence/distributions/_mixture.py
def diagnostics(self) -> MixtureDiagnostics:
    """Summarize component weights and covariance conditioning.

    Returns
    -------
    MixtureDiagnostics
        Component and feature counts, weight sum and extrema, weight entropy
        in nats, and independent read-only per-component condition numbers.
    """
    weight_sum = float(np.sum(self.weights))
    max_weight = float(np.max(self.weights))
    min_weight = float(np.min(self.weights))
    weight_entropy = float(-np.sum(self.weights * np.log(self.weights + 1e-12)))
    covariance_condition_numbers = readonly_copy(
        np.linalg.cond(self.covariances), dtype=np.float64
    )
    return MixtureDiagnostics(
        n_components=self.n_components,
        n_features=self.n_features,
        weight_sum=weight_sum,
        max_weight=max_weight,
        min_weight=min_weight,
        weight_entropy=weight_entropy,
        covariance_condition_numbers=covariance_condition_numbers,
    )

from_components classmethod

from_components(
    components: Sequence[Gaussian], *, weights: ArrayLike | None = None
) -> GaussianMixture

Create a mixture from fixed Gaussian components.

Parameters:

  • components (sequence of Gaussian) –

    Nonempty sequence of components with equal feature dimensions.

  • weights (array-like, shape (n_components,), or None, default: None ) –

    Finite, nonnegative coefficients with positive total mass. They are normalized; None assigns equal component weights.

Returns:

  • GaussianMixture –

    Independent mixture preserving the supplied component order.

Source code in src/gmm_divergence/distributions/_mixture.py
@classmethod
def from_components(
    cls, components: Sequence[Gaussian], *, weights: npt.ArrayLike | None = None
) -> GaussianMixture:
    """Create a mixture from fixed Gaussian components.

    Parameters
    ----------
    components : sequence of Gaussian
        Nonempty sequence of components with equal feature dimensions.
    weights : array-like, shape (n_components,), or None, default=None
        Finite, nonnegative coefficients with positive total mass. They
        are normalized; None assigns equal component weights.

    Returns
    -------
    GaussianMixture
        Independent mixture preserving the supplied component order.
    """
    if not components:
        msg = "components must contain at least one Gaussian."
        raise ValueError(msg)
    means = np.array([comp.mean for comp in components], dtype=np.float64)
    covariances = np.array([comp.covariance for comp in components], dtype=np.float64)
    if weights is None:
        weights = np.ones(len(components), dtype=np.float64) / len(components)
    else:
        weights = np.asarray(weights, dtype=np.float64)
    return cls(weights=weights, means=means, covariances=covariances)

from_sklearn classmethod

from_sklearn(gmm: GaussianMixture) -> GaussianMixture

Convert a fitted scikit-learn mixture to full covariance matrices.

Parameters:

  • gmm (GaussianMixture) –

    Fitted estimator using full, tied, diagonal, or spherical covariance.

Returns:

  • GaussianMixture –

    Independent distribution with the same component order and weights.

Raises:

  • ValueError –

    If the estimator is unfitted or its covariance type is unsupported.

Source code in src/gmm_divergence/distributions/_mixture.py
@classmethod
def from_sklearn(cls, gmm: SklearnGaussianMixture) -> GaussianMixture:
    """Convert a fitted scikit-learn mixture to full covariance matrices.

    Parameters
    ----------
    gmm : sklearn.mixture.GaussianMixture
        Fitted estimator using full, tied, diagonal, or spherical covariance.

    Returns
    -------
    GaussianMixture
        Independent distribution with the same component order and weights.

    Raises
    ------
    ValueError
        If the estimator is unfitted or its covariance type is unsupported.
    """
    if not all(hasattr(gmm, name) for name in ("means_", "weights_", "covariances_")):
        msg = "gmm must be fitted before conversion with from_sklearn."
        raise ValueError(msg)
    means = np.array(gmm.means_, dtype=np.float64)
    weights = as_weights(gmm.weights_)
    sklearn_covariances = np.array(gmm.covariances_, dtype=np.float64)
    n_components, n_features = means.shape
    covariance_type = cast("str", gmm.get_params()["covariance_type"])
    match covariance_type:
        case "full":
            covariances = sklearn_covariances
        case "tied":
            covariances = np.repeat(sklearn_covariances[None, :, :], n_components, axis=0)
        case "diag":
            covariances = sklearn_covariances[:, :, None] * np.eye(n_features)
        case "spherical":
            covariances = sklearn_covariances[:, None, None] * np.eye(n_features)
        case _:
            msg = f"Unsupported sklearn covariance type: {covariance_type!r}."
            raise ValueError(msg)
    return cls(weights=weights, means=means, covariances=covariances)

get_component

get_component(index: int) -> Gaussian

Return a Gaussian component independently of the mixture.

Parameters:

  • index (int) –

    Component position in [0, n_components). Negative indices and booleans are not accepted.

Returns:

  • Gaussian –

    Gaussian with copied parameters from the requested component.

Notes

Index validation raises TypeError for noninteger positions and IndexError for positions outside the component range.

Source code in src/gmm_divergence/distributions/_mixture.py
def get_component(self, index: int) -> Gaussian:
    """Return a Gaussian component independently of the mixture.

    Parameters
    ----------
    index : int
        Component position in `[0, n_components)`. Negative indices and
        booleans are not accepted.

    Returns
    -------
    Gaussian
        Gaussian with copied parameters from the requested component.

    Notes
    -----
    Index validation raises TypeError for noninteger positions and
    IndexError for positions outside the component range.
    """
    validate_index(index, self.n_components)

    return Gaussian(mean=self.means[index], covariance=self.covariances[index])

log_determinants

log_determinants() -> FloatArray

Return cached covariance log-determinants, shape (n_components,).

The returned float64 array is read-only and uses natural logarithms.

Source code in src/gmm_divergence/distributions/_mixture.py
def log_determinants(self) -> FloatArray:
    """Return cached covariance log-determinants, shape (n_components,).

    The returned float64 array is read-only and uses natural logarithms.
    """
    if self._log_dets is not None:
        return self._log_dets

    cholesky = self.cholesky()
    log_determinants = logdet_from_cholesky(cholesky)
    log_determinants.setflags(write=False)
    object.__setattr__(self, "_log_dets", log_determinants)
    return log_determinants

logpdf

logpdf(x: ArrayLike) -> FloatArray

Evaluate natural-log mixture densities at one or more points.

Parameters:

  • x ((array - like, shape(n_features) or (n_points, n_features))) –

    Finite observations. A 1D input represents one observation.

Returns:

  • (ndarray, shape(n_points)) –

    Log densities, including a length-one array for a single point.

Source code in src/gmm_divergence/distributions/_mixture.py
def logpdf(self, x: npt.ArrayLike) -> FloatArray:
    """Evaluate natural-log mixture densities at one or more points.

    Parameters
    ----------
    x : array-like, shape (n_features,) or (n_points, n_features)
        Finite observations. A 1D input represents one observation.

    Returns
    -------
    ndarray, shape (n_points,)
        Log densities, including a length-one array for a single point.
    """
    return gmm_logpdf(x=x, gmm=self)

moment_match

moment_match() -> Gaussian

Approximate the mixture with a Gaussian sharing its aggregate moments.

Returns:

  • Gaussian –

    Gaussian with the mixture mean and covariance, including the covariance contributed by differences between component means.

Source code in src/gmm_divergence/distributions/_mixture.py
def moment_match(self) -> Gaussian:
    """Approximate the mixture with a Gaussian sharing its aggregate moments.

    Returns
    -------
    Gaussian
        Gaussian with the mixture mean and covariance, including the
        covariance contributed by differences between component means.
    """
    return Gaussian(self.mean, self.covariance)

pdf

pdf(x: ArrayLike) -> FloatArray

Evaluate mixture densities at one or more points.

Parameters:

  • x ((array - like, shape(n_features) or (n_points, n_features))) –

    Finite observations. A 1D input represents one observation.

Returns:

  • (ndarray, shape(n_points)) –

    Densities, including a length-one array for a single point.

Source code in src/gmm_divergence/distributions/_mixture.py
def pdf(self, x: npt.ArrayLike) -> FloatArray:
    """Evaluate mixture densities at one or more points.

    Parameters
    ----------
    x : array-like, shape (n_features,) or (n_points, n_features)
        Finite observations. A 1D input represents one observation.

    Returns
    -------
    ndarray, shape (n_points,)
        Densities, including a length-one array for a single point.
    """
    return np.exp(self.logpdf(x))

responsibilities

responsibilities(x: ArrayLike) -> FloatArray

Compute the responsibilities of each component for the given points.

Parameters:

  • x ((array - like, shape(n_features) or (n_samples, n_features))) –

    Finite points at which to compute responsibilities. A 1D input represents one observation.

Returns:

  • responsibilities ( (array, shape(n_samples, n_components)) ) –

    The responsibilities of each component for each point, normalized to sum to 1 across components.

Source code in src/gmm_divergence/distributions/_mixture.py
def responsibilities(self, x: npt.ArrayLike) -> FloatArray:
    """Compute the responsibilities of each component for the given points.

    Parameters
    ----------
    x : array-like, shape (n_features,) or (n_samples, n_features)
        Finite points at which to compute responsibilities. A 1D input
        represents one observation.

    Returns
    -------
    responsibilities : array, shape (n_samples, n_components)
        The responsibilities of each component for each point, normalized to
        sum to 1 across components.
    """
    x = as_points(x, n_features=self.n_features, name="x")
    if self.n_components == 1:
        return np.ones((x.shape[0], 1), dtype=np.float64)

    with np.errstate(divide="ignore"):
        log_terms = _component_logpdf(self, x) + np.log(self.weights)[None, :]
    return np.exp(log_terms - logsumexp(log_terms, axis=1)[:, None])

sample

sample(n_samples: int, *, rng: Generator | int | None = None) -> FloatArray

Draw independent observations from the mixture.

Parameters:

  • n_samples (int) –

    Positive number of observations to draw.

  • rng (numpy.random.Generator, int, or None, default: None ) –

    Random source. An integer restarts a reproducible stream on each call; a generator advances its state. None uses fresh entropy.

Returns:

  • (ndarray, shape(n_samples, n_features)) –

    Newly allocated float64 observations in random component order.

Source code in src/gmm_divergence/distributions/_mixture.py
def sample(self, n_samples: int, *, rng: np.random.Generator | int | None = None) -> FloatArray:
    """Draw independent observations from the mixture.

    Parameters
    ----------
    n_samples : int
        Positive number of observations to draw.
    rng : numpy.random.Generator, int, or None, default=None
        Random source. An integer restarts a reproducible stream on each
        call; a generator advances its state. None uses fresh entropy.

    Returns
    -------
    ndarray, shape (n_samples, n_features)
        Newly allocated float64 observations in random component order.
    """
    return sample_gmm(self, n_samples=n_samples, rng=rng)

select_components

select_components(indices: ArrayLike) -> GaussianMixture

Select components in the requested order and normalize their weights.

Parameters:

  • indices ((array - like, shape(n_selected))) –

    Nonempty vector of integer positions in [0, n_components). Repeated positions are allowed. Selected weights must have positive total mass.

Returns:

  • GaussianMixture –

    Independent mixture in the requested order, retaining mapping rows.

Raises:

  • IndexError –

    If a component position is out of range.

Notes

Input validation raises TypeError for a noninteger dtype and ValueError for an invalid index shape or zero selected mass.

Source code in src/gmm_divergence/distributions/_mixture.py
def select_components(self, indices: npt.ArrayLike) -> GaussianMixture:
    """Select components in the requested order and normalize their weights.

    Parameters
    ----------
    indices : array-like, shape (n_selected,)
        Nonempty vector of integer positions in `[0, n_components)`.
        Repeated positions are allowed. Selected weights must have positive
        total mass.

    Returns
    -------
    GaussianMixture
        Independent mixture in the requested order, retaining mapping rows.

    Raises
    ------
    IndexError
        If a component position is out of range.

    Notes
    -----
    Input validation raises TypeError for a noninteger dtype and ValueError
    for an invalid index shape or zero selected mass.
    """
    indices = index_array(indices, name="indices")
    if np.any(indices < 0) or np.any(indices >= self.n_components):
        msg = f"Component indices must be in the range [0, {self.n_components})."
        raise IndexError(msg)

    return GaussianMixture(
        weights=as_weights(self.weights[indices], expected_length=indices.shape[0]),
        means=self.means[indices],
        covariances=self.covariances[indices],
        mapping=None
        if self.mapping is None
        else MixtureMapping(
            source_index=self.mapping.source_index[indices],
            local_component_index=self.mapping.local_component_index[indices],
        ),
    )

to_sklearn

to_sklearn() -> GaussianMixture

Convert to a sklearn mixture ready for evaluation and sampling.

Parameters are copied without fitting data. Optimization history and convergence diagnostics are unavailable because no fitting is performed.

Returns:

  • GaussianMixture –

    Estimator with independent parameter arrays and full covariances. Mixture provenance is not transferred.

Source code in src/gmm_divergence/distributions/_mixture.py
def to_sklearn(self) -> SklearnGaussianMixture:
    """Convert to a sklearn mixture ready for evaluation and sampling.

    Parameters are copied without fitting data. Optimization history and
    convergence diagnostics are unavailable because no fitting is performed.

    Returns
    -------
    sklearn.mixture.GaussianMixture
        Estimator with independent parameter arrays and full covariances.
        Mixture provenance is not transferred.
    """
    mixture = SklearnGaussianMixture(n_components=self.n_components, covariance_type="full")
    mixture.weights_ = self.weights.copy()
    mixture.means_ = self.means.copy()
    mixture.covariances_ = self.covariances.copy()
    # Sklearn uses upper triangular factors U such that precision = U @ U.T.
    inverse_chol = np.linalg.solve(
        self.cholesky(), np.broadcast_to(np.eye(self.n_features), self.covariances.shape)
    )
    precision_chol = np.swapaxes(inverse_chol, -1, -2)
    mixture.precisions_cholesky_ = precision_chol
    mixture.precisions_ = precision_chol @ np.swapaxes(precision_chol, -1, -2)
    mixture.n_features_in_ = self.n_features
    return mixture

combine_distributions

combine_distributions(
    sources: Sequence[GaussianDistribution], *, weights: ArrayLike | None = None
) -> GaussianMixture

Combine fixed distributions with nonnegative source weights.

Coefficients are normalized; omitted weights give equal source mass. The returned mixture works directly with divergence and fitting APIs. Its mapping identifies immediate source indices and local component indices, even when an input source already carries provenance.

Parameters:

  • sources (sequence of Gaussian or GaussianMixture) –

    Nonempty sequence of distributions with the same number of features. Components are flattened in source order, then local component order.

  • weights (array-like, shape (n_sources,), or None, default: None ) –

    Finite, nonnegative source coefficients with positive total mass. Coefficients are normalized; None assigns equal mass to each source.

Returns:

  • GaussianMixture –

    Combined distribution with independent, read-only parameter arrays and a mapping to the immediate sources. Zero-weight components remain.

Source code in src/gmm_divergence/distributions/_combine.py
def combine_distributions(
    sources: Sequence[GaussianDistribution], *, weights: npt.ArrayLike | None = None
) -> GaussianMixture:
    """Combine fixed distributions with nonnegative source weights.

    Coefficients are normalized; omitted weights give equal source mass.
    The returned mixture works directly with divergence and fitting APIs.
    Its mapping identifies immediate source indices and local component indices,
    even when an input source already carries provenance.

    Parameters
    ----------
    sources : sequence of Gaussian or GaussianMixture
        Nonempty sequence of distributions with the same number of features.
        Components are flattened in source order, then local component order.
    weights : array-like, shape (n_sources,), or None, default=None
        Finite, nonnegative source coefficients with positive total mass.
        Coefficients are normalized; None assigns equal mass to each source.

    Returns
    -------
    GaussianMixture
        Combined distribution with independent, read-only parameter arrays
        and a mapping to the immediate sources. Zero-weight components remain.
    """
    if not sources:
        msg = "sources must contain at least one distribution."
        raise ValueError(msg)
    if len({source.n_features for source in sources}) != 1:
        msg = "sources must have the same n_features."
        raise ValueError(msg)
    source_weights = as_weights(
        np.ones(len(sources)) if weights is None else weights,
        expected_length=len(sources),
        name="weights",
    )
    arrays = [source.component_arrays() for source in sources]
    return GaussianMixture(
        weights=np.concatenate([
            weight * parts[0] for weight, parts in zip(source_weights, arrays, strict=True)
        ]),
        means=np.concatenate([parts[1] for parts in arrays]),
        covariances=np.concatenate([parts[2] for parts in arrays]),
        mapping=MixtureMapping(
            source_index=np.concatenate([
                np.full(len(parts[0]), index, dtype=np.intp) for index, parts in enumerate(arrays)
            ]),
            local_component_index=np.concatenate([
                np.arange(len(parts[0]), dtype=np.intp) for parts in arrays
            ]),
        ),
    )

Divergence Helpers

categorical_kl_divergence

categorical_kl_divergence(
    p: ArrayLike, q: ArrayLike, *, epsilon: float = 0.0
) -> DivergenceResult

Compute directed categorical KL between probability vectors over shared categories.

For probability vectors \(\boldsymbol{\pi}_p\) and \(\boldsymbol{\pi}_q\) over \(K\) shared categories, the exact quantity is

\[ D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q) =\sum_{k:\pi_{p,k}>0}\pi_{p,k}\log\frac{\pi_{p,k}}{\pi_{q,k}}. \]

Parameters:

  • p (array - like) –

    Nonempty, finite, nonnegative probability vectors of equal length, each summing to one. Index k must represent the same category in both vectors; the caller is responsible for this correspondence. Sums are checked with rtol=1e-7, atol=1e-8; negative values are rejected without clipping.

  • q (array - like) –

    Nonempty, finite, nonnegative probability vectors of equal length, each summing to one. Index k must represent the same category in both vectors; the caller is responsible for this correspondence. Sums are checked with rtol=1e-7, atol=1e-8; negative values are rejected without clipping.

  • epsilon (float, default: 0.0 ) –

    Finite, nonnegative additive smoothing amount. For K categories, each vector becomes (probabilities + epsilon) / (1 + K * epsilon). Smoothing changes the probability distributions being compared.

Returns:

  • DivergenceResult –

    Categorical \(D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q)\) in nats with divergence "categorical_kl". The vectors are the supplied p and q probabilities, after smoothing if requested. Without smoothing, a positive reference probability paired with a zero comparison probability gives positive infinity.

Notes

Categories may represent mode occupancies or any other shared outcomes. When comparing Gaussian mixture weights, the caller must align components; independently fitted mixtures may order components differently, and components need not represent distinct modes. Inputs are not modified.

Source code in src/gmm_divergence/divergence/_api.py
def categorical_kl_divergence(
    p: npt.ArrayLike, q: npt.ArrayLike, *, epsilon: float = 0.0
) -> DivergenceResult:
    r"""Compute directed categorical KL between probability vectors over shared categories.

    For probability vectors $\boldsymbol{\pi}_p$ and $\boldsymbol{\pi}_q$ over
    $K$ shared categories, the exact quantity is

    $$
    D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q)
    =\sum_{k:\pi_{p,k}>0}\pi_{p,k}\log\frac{\pi_{p,k}}{\pi_{q,k}}.
    $$

    Parameters
    ----------
    p, q : array-like
        Nonempty, finite, nonnegative probability vectors of equal length,
        each summing to one. Index `k` must represent the same category in
        both vectors; the caller is responsible for this correspondence.
        Sums are checked with `rtol=1e-7`, `atol=1e-8`; negative values are
        rejected without clipping.
    epsilon : float, default=0.0
        Finite, nonnegative additive smoothing amount. For `K` categories,
        each vector becomes `(probabilities + epsilon) / (1 + K * epsilon)`.
        Smoothing changes the probability distributions being compared.

    Returns
    -------
    DivergenceResult
        Categorical $D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q)$
        in nats with divergence `"categorical_kl"`. The vectors are the supplied
        p and q probabilities, after smoothing if requested. Without smoothing,
        a positive reference probability paired with a zero comparison
        probability gives positive infinity.

    Notes
    -----
    Categories may represent mode occupancies or any other shared outcomes.
    When comparing Gaussian mixture weights, the caller must align components;
    independently fitted mixtures may order components differently, and
    components need not represent distinct modes. Inputs are not modified.
    """
    return kl_categorical(p, q, epsilon=epsilon)

kl_divergence

kl_divergence(
    p: GaussianDistribution, q: GaussianDistribution, *, estimator: KLEstimator
) -> DivergenceResult

Compute the directed Kullback-Leibler divergence \(D_{\mathrm{KL}}(p \| q)\).

Computes

\[ D_{\mathrm{KL}}(p \| q) = \mathbb{E}_{X \sim p}[\log p(X) - \log q(X)]. \]

The estimator is always explicit: it is never replaced automatically when the inputs happen to be Gaussian. Select :class:ClosedForm for an exact Gaussian-to-Gaussian result, or a sampled or approximate estimator for mixtures.

Parameters:

  • p (Gaussian or GaussianMixture) –

    Reference and comparison distributions. They must have equal dimensionality; the divergence is evaluated from p to q.

  • q (Gaussian or GaussianMixture) –

    Reference and comparison distributions. They must have equal dimensionality; the divergence is evaluated from p to q.

  • estimator (KLEstimator) –

    Explicit estimator configuration. ClosedForm requires two :class:Gaussian inputs. MonteCarlo samples from p; therefore sampling.Samples must contain samples drawn from p.

Returns:

  • DivergenceResult –

    KL estimate in nats with the supplied estimator configuration. n_evaluations counts integration points when applicable; monte_carlo contains sampling counts and supported uncertainty estimates.

Notes

Approximate or finite-sample estimates may be negative and are not clipped.

Source code in src/gmm_divergence/divergence/_api.py
def kl_divergence(
    p: GaussianDistribution, q: GaussianDistribution, *, estimator: KLEstimator
) -> DivergenceResult:
    r"""Compute the directed Kullback-Leibler divergence $D_{\mathrm{KL}}(p \| q)$.

    Computes

    $$
    D_{\mathrm{KL}}(p \| q)
    = \mathbb{E}_{X \sim p}[\log p(X) - \log q(X)].
    $$

    The estimator is always explicit: it is never replaced automatically when
    the inputs happen to be Gaussian. Select :class:`ClosedForm` for an exact
    Gaussian-to-Gaussian result, or a sampled or approximate estimator for
    mixtures.

    Parameters
    ----------
    p, q : Gaussian or GaussianMixture
        Reference and comparison distributions. They must have equal
        dimensionality; the divergence is evaluated from `p` to `q`.
    estimator : KLEstimator
        Explicit estimator configuration. `ClosedForm` requires two
        :class:`Gaussian` inputs. `MonteCarlo` samples from `p`; therefore
        `sampling.Samples` must contain samples drawn from `p`.

    Returns
    -------
    DivergenceResult
        KL estimate in nats with the supplied estimator configuration.
        `n_evaluations` counts integration points when applicable;
        `monte_carlo` contains sampling counts and supported uncertainty estimates.

    Notes
    -----
    Approximate or finite-sample estimates may be negative and are not clipped.

    """
    _validate_same_dimension(p, q)
    match estimator:
        case MonteCarlo():
            result = kl_monte_carlo(p, q, estimator=estimator)
        case Unscented():
            result = kl_unscented(p, q)
        case MomentMatchedGaussian():
            result = kl_gaussian_approximation(p, q)
        case ClosedForm():
            p_gaussian, q_gaussian = _require_gaussian_pair(p, q)
            result = kl_closed_form(p_gaussian, q_gaussian)
        case Variational():
            result = kl_variational(p, q)
    return replace(result, estimator=estimator)

symmetric_kl_divergence

symmetric_kl_divergence(
    p: GaussianDistribution,
    q: GaussianDistribution,
    *,
    forward: KLEstimator,
    reverse: KLEstimator,
) -> DivergenceResult

Compute the averaged symmetric Kullback-Leibler divergence.

Computes

\[ D_{\mathrm{SKL}}(p, q) = \frac{1}{2}\left[D_{\mathrm{KL}}(p \| q) + D_{\mathrm{KL}}(q \| p)\right]. \]

Here \(p\) and \(q\) are the reference and comparison distributions. The quantity is the average, not the unscaled sum, of directed KL values in nats. The directional estimators are intentionally separate. In particular, precomputed samples for forward must originate from p, while those for reverse must originate from q.

Parameters:

Returns:

  • DivergenceResult –

    Average of the directed estimates in nats. terms holds forward then reverse results. n_evaluations is summed only when both directions report evaluation counts; uncertainty remains on the directional terms.

Source code in src/gmm_divergence/divergence/_api.py
def symmetric_kl_divergence(
    p: GaussianDistribution, q: GaussianDistribution, *, forward: KLEstimator, reverse: KLEstimator
) -> DivergenceResult:
    r"""Compute the averaged symmetric Kullback-Leibler divergence.

    Computes

    $$
    D_{\mathrm{SKL}}(p, q)
    = \frac{1}{2}\left[D_{\mathrm{KL}}(p \| q) + D_{\mathrm{KL}}(q \| p)\right].
    $$

    Here $p$ and $q$ are the reference and comparison distributions. The quantity
    is the average, not the unscaled sum, of directed KL values in nats.
    The directional estimators are intentionally separate. In particular,
    precomputed samples for `forward` must originate from `p`, while those
    for `reverse` must originate from `q`.

    Parameters
    ----------
    p, q : Gaussian or GaussianMixture
        Distributions to compare. They must have equal dimensionality.
    forward : KLEstimator
        Estimator for $D_{\mathrm{KL}}(p \| q)$.
    reverse : KLEstimator
        Estimator for $D_{\mathrm{KL}}(q \| p)$.

    Returns
    -------
    DivergenceResult
        Average of the directed estimates in nats. `terms` holds forward then
        reverse results. `n_evaluations` is summed only when both directions
        report evaluation counts; uncertainty remains on the directional terms.

    """
    forward_result = kl_divergence(p, q, estimator=forward)
    reverse_result = kl_divergence(q, p, estimator=reverse)
    return DivergenceResult(
        value=0.5 * (forward_result.value + reverse_result.value),
        divergence="symmetric_kl",
        terms=(forward_result, reverse_result),
        n_evaluations=_sum_evaluations(forward_result, reverse_result),
    )

jensen_shannon_divergence

jensen_shannon_divergence(
    p: GaussianDistribution,
    q: GaussianDistribution,
    *,
    p_to_midpoint: KLEstimator,
    q_to_midpoint: KLEstimator,
) -> DivergenceResult

Compute the Jensen-Shannon divergence between two distributions.

Computes

\[ D_{\mathrm{JS}}(p, q) = \frac{1}{2}D_{\mathrm{KL}}(p \| m) + \frac{1}{2}D_{\mathrm{KL}}(q \| m), \qquad m = \frac{1}{2}p + \frac{1}{2}q. \]

The midpoint is represented as a Gaussian mixture. Each directed term has an independent estimator so that precomputed samples remain attached to the distribution from which they were drawn.

Parameters:

  • p (Gaussian or GaussianMixture) –

    Distributions to compare. They must have equal dimensionality.

  • q (Gaussian or GaussianMixture) –

    Distributions to compare. They must have equal dimensionality.

  • p_to_midpoint (KLEstimator) –

    Estimator for \(D_{\mathrm{KL}}(p \| m)\). Any supplied samples must be drawn from p.

  • q_to_midpoint (KLEstimator) –

    Estimator for \(D_{\mathrm{KL}}(q \| m)\). Any supplied samples must be drawn from q.

Returns:

  • DivergenceResult –

    Jensen-Shannon divergence in nats, without taking its square root. terms holds the p-to-midpoint then q-to-midpoint results. n_evaluations is summed only when both terms report evaluation counts; uncertainty remains on the directional terms.

Notes

ClosedForm is unsuitable because the midpoint is a GaussianMixture. The exact divergence is bounded by log(2); approximations need not preserve this bound and are not clipped.

Source code in src/gmm_divergence/divergence/_api.py
def jensen_shannon_divergence(
    p: GaussianDistribution,
    q: GaussianDistribution,
    *,
    p_to_midpoint: KLEstimator,
    q_to_midpoint: KLEstimator,
) -> DivergenceResult:
    r"""Compute the Jensen-Shannon divergence between two distributions.

    Computes

    $$
    D_{\mathrm{JS}}(p, q)
    = \frac{1}{2}D_{\mathrm{KL}}(p \| m)
    + \frac{1}{2}D_{\mathrm{KL}}(q \| m),
    \qquad m = \frac{1}{2}p + \frac{1}{2}q.
    $$

    The midpoint is represented as a Gaussian mixture. Each directed term has
    an independent estimator so that precomputed samples remain attached to
    the distribution from which they were drawn.

    Parameters
    ----------
    p, q : Gaussian or GaussianMixture
        Distributions to compare. They must have equal dimensionality.
    p_to_midpoint : KLEstimator
        Estimator for $D_{\mathrm{KL}}(p \| m)$. Any supplied samples must be drawn from
        `p`.
    q_to_midpoint : KLEstimator
        Estimator for $D_{\mathrm{KL}}(q \| m)$. Any supplied samples must be drawn from
        `q`.

    Returns
    -------
    DivergenceResult
        Jensen-Shannon divergence in nats, without taking its square root.
        `terms` holds the p-to-midpoint then q-to-midpoint results.
        `n_evaluations` is summed only when both terms report evaluation counts;
        uncertainty remains on the directional terms.

    Notes
    -----
    ClosedForm is unsuitable because the midpoint is a GaussianMixture.
    The exact divergence is bounded by log(2); approximations need not preserve
    this bound and are not clipped.

    """
    _validate_same_dimension(p, q)
    midpoint = combine_distributions([p, q], weights=[0.5, 0.5])
    p_result = kl_divergence(p, midpoint, estimator=p_to_midpoint)
    q_result = kl_divergence(q, midpoint, estimator=q_to_midpoint)
    return DivergenceResult(
        value=0.5 * (p_result.value + q_result.value),
        divergence="jensen_shannon",
        terms=(p_result, q_result),
        n_evaluations=_sum_evaluations(p_result, q_result),
    )

component_kl_matrix

component_kl_matrix(
    p: GaussianDistribution, q: GaussianDistribution
) -> FloatArray

Return pairwise closed-form KL divergences between components.

The result has shape (p_components, q_components) and element (k, j) equals \(D_{\mathrm{KL}}(p_k \| q_j)\), where \(p_k\) and \(q_j\) are Gaussian component densities of p and q. A :class:Gaussian is treated as a one-component mixture.

Parameters:

  • p (Gaussian or GaussianMixture) –

    Distributions whose Gaussian components are compared. They must have equal dimensionality.

  • q (Gaussian or GaussianMixture) –

    Distributions whose Gaussian components are compared. They must have equal dimensionality.

Returns:

  • FloatArray –

    A float64 diagnostic matrix. It is not the KL divergence between the full mixtures.

Source code in src/gmm_divergence/divergence/_api.py
def component_kl_matrix(p: GaussianDistribution, q: GaussianDistribution) -> FloatArray:
    r"""Return pairwise closed-form KL divergences between components.

    The result has shape `(p_components, q_components)` and element
    `(k, j)` equals $D_{\mathrm{KL}}(p_k \| q_j)$, where $p_k$ and $q_j$ are
    Gaussian component densities of p and q. A :class:`Gaussian` is treated as a
    one-component mixture.

    Parameters
    ----------
    p, q : Gaussian or GaussianMixture
        Distributions whose Gaussian components are compared. They must have
        equal dimensionality.

    Returns
    -------
    FloatArray
        A `float64` diagnostic matrix. It is not the KL divergence between
        the full mixtures.

    """
    _validate_same_dimension(p, q)
    _, p_means, p_covariances = p.component_arrays()
    _, q_means, q_covariances = q.component_arrays()
    return pairwise_gaussian_kl(p_means, p_covariances, q_means, q_covariances)

aligned_joint_kl_divergence

aligned_joint_kl_divergence(
    p: GaussianMixture, q: GaussianMixture
) -> AlignedJointKLResult

Compute joint KL of component labels and observations with aligned components.

Given two Gaussian mixtures with corresponding component indices,

\[ p(k,x) = \pi_{p,k}\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k}), \]
\[ q(k,x) = \pi_{q,k}\mathcal{N}(x;\mu_{q,k},\Sigma_{q,k}), \]

compute the exact joint KL divergence:

\[ D_{\mathrm{KL}}(p(k,x)\|q(k,x)) = D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q) + \sum_{k=1}^{K} \pi_{p,k} D_{\mathrm{KL}}(p_k\|q_k). \]

Here \(k\in\{1,\ldots,K\}\) is a shared component label, \(x\in\mathbb{R}^d\) an observation, and \(\boldsymbol{\pi}_p\), \(\boldsymbol{\pi}_q\) the component probability vectors. The conditional densities are \(p_k(x)=\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k})\) and analogously \(q_k(x)\). Covariances are positive-definite \(d\times d\) matrices. This compares the joint distributions of component label and observation, assuming component indices correspond. No component matching is performed. Marginalizing over the label gives p(x) and q(x); their KL cannot exceed this joint KL. The two quantities are not generally equal. Values are in nats.

Parameters:

  • p (GaussianMixture) –

    Gaussian mixtures with equal numbers of components and equal feature dimensions. Component indices must be aligned.

  • q (GaussianMixture) –

    Gaussian mixtures with equal numbers of components and equal feature dimensions. Component indices must be aligned.

Returns:

  • AlignedJointKLResult –

    KL decomposition containing:

    • value: Total joint KL divergence.
    • weight_kl: KL divergence between mixture weights.
    • component_kls: Individual Gaussian component KL values.
    • weighted_component_kl: Weighted sum of component KL values.
Source code in src/gmm_divergence/divergence/methods/_aligned_component.py
def aligned_joint_kl_divergence(p: GaussianMixture, q: GaussianMixture) -> AlignedJointKLResult:
    r"""Compute joint KL of component labels and observations with aligned components.

    Given two Gaussian mixtures with corresponding component indices,

    $$
    p(k,x) = \pi_{p,k}\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k}),
    $$

    $$
    q(k,x) = \pi_{q,k}\mathcal{N}(x;\mu_{q,k},\Sigma_{q,k}),
    $$

    compute the exact joint KL divergence:

    $$
    D_{\mathrm{KL}}(p(k,x)\|q(k,x))
    =
    D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q)
    +
    \sum_{k=1}^{K}
    \pi_{p,k}
    D_{\mathrm{KL}}(p_k\|q_k).
    $$

    Here $k\in\{1,\ldots,K\}$ is a shared component label, $x\in\mathbb{R}^d$
    an observation, and $\boldsymbol{\pi}_p$, $\boldsymbol{\pi}_q$ the component
    probability vectors. The conditional densities are
    $p_k(x)=\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k})$ and analogously $q_k(x)$.
    Covariances are positive-definite $d\times d$ matrices.
    This compares the joint distributions of component label and observation,
    assuming component indices correspond. No component matching is performed.
    Marginalizing over the label gives p(x) and q(x); their KL cannot exceed
    this joint KL. The two quantities are not generally equal. Values are in nats.

    Parameters
    ----------
    p, q : GaussianMixture
        Gaussian mixtures with equal numbers of components and
        equal feature dimensions. Component indices must be aligned.

    Returns
    -------
    AlignedJointKLResult
        KL decomposition containing:

        - `value`: Total joint KL divergence.
        - `weight_kl`: KL divergence between mixture weights.
        - `component_kls`: Individual Gaussian component KL values.
        - `weighted_component_kl`: Weighted sum of component KL values.
    """
    _validate_mixture(p, name="p")
    _validate_mixture(q, name="q")
    if p.n_components != q.n_components:
        msg = (
            "Aligned-component KL requires equal numbers of components, "
            f"got {p.n_components} and {q.n_components}."
        )
        raise ValueError(msg)

    if p.n_features != q.n_features:
        msg = (
            f"Aligned-component KL requires equal feature dimensions, got "
            f"{p.n_features} and {q.n_features}."
        )
        raise ValueError(msg)

    weight_kl = kl_categorical(p.weights, q.weights).value

    component_kls = gaussian_kl_from_factors(
        p.covariances, q.means - p.means, q.cholesky(), p.log_determinants(), q.log_determinants()
    )
    component_kls.setflags(write=False)
    weighted_component_kl = float(np.dot(p.weights, component_kls))

    return AlignedJointKLResult(
        value=weight_kl + weighted_component_kl,
        weight_kl=weight_kl,
        component_kls=component_kls,
        weighted_component_kl=weighted_component_kl,
    )

Fitting Helpers

fit_categorical_weights

fit_categorical_weights(
    target: ArrayLike, candidates: ArrayLike, *, optimizer: Optimizer
) -> CategoricalWeightFitResult

Fit a weighted mixture of categorical distributions using forward KL.

Find nonnegative candidate weights that sum to one and minimize

\[ D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_{\mathbf{w}}) =\sum_{k:\pi_{p,k}>0}\pi_{p,k} \log\frac{\pi_{p,k}}{\pi_{\mathbf{w},k}}, \qquad \pi_{\mathbf{w},k}=\sum_{i=1}^{L}w_i\pi_{i,k}, \]

where \(\boldsymbol{\pi}_p\) is the target probability vector over \(K\) categories, \(\pi_{i,k}\) is candidate \(i\)'s probability of category \(k\), and \(\mathbf{w}\in\Delta_L\) has \(L\) nonnegative candidate weights summing to one. Indices refer to the same categories in every probability vector.

Parameters:

  • target ((array - like, shape(n_categories))) –

    Target categorical probability distribution.

  • candidates ((array - like, shape(n_candidates, n_categories))) –

    Candidate probability distributions, one per row.

  • optimizer (Optimizer) –

    Explicit optimizer configuration. Initial vectors have one entry per candidate row.

Returns:

  • CategoricalWeightFitResult –

    Optimized candidate weights, fitted categorical probabilities, KL divergence, and optimizer convergence information.

Notes

Probabilities must be finite and strictly nonnegative. Target and candidate rows must sum to one within rtol=1e-7, atol=1e-8. Inputs are not normalized or clipped.

Every category with positive target mass must have positive mass in at least one candidate. The objective is evaluated exactly over categories; it uses no sampling or approximation. Only forward KL fitting is supported.

Source code in src/gmm_divergence/fitting/_api.py
def fit_categorical_weights(
    target: npt.ArrayLike, candidates: npt.ArrayLike, *, optimizer: Optimizer
) -> CategoricalWeightFitResult:
    r"""Fit a weighted mixture of categorical distributions using forward KL.

    Find nonnegative candidate weights that sum to one and minimize

    $$
    D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_{\mathbf{w}})
    =\sum_{k:\pi_{p,k}>0}\pi_{p,k}
    \log\frac{\pi_{p,k}}{\pi_{\mathbf{w},k}},
    \qquad \pi_{\mathbf{w},k}=\sum_{i=1}^{L}w_i\pi_{i,k},
    $$

    where $\boldsymbol{\pi}_p$ is the target probability vector over $K$
    categories, $\pi_{i,k}$ is candidate $i$'s probability of category $k$, and
    $\mathbf{w}\in\Delta_L$ has $L$ nonnegative candidate weights summing to one.
    Indices refer to the same categories in every probability vector.

    Parameters
    ----------
    target : array-like, shape (n_categories,)
        Target categorical probability distribution.
    candidates : array-like, shape (n_candidates, n_categories)
        Candidate probability distributions, one per row.
    optimizer : Optimizer
        Explicit optimizer configuration. Initial vectors have one entry per
        candidate row.

    Returns
    -------
    CategoricalWeightFitResult
        Optimized candidate weights, fitted categorical probabilities,
        KL divergence, and optimizer convergence information.

    Notes
    -----
    Probabilities must be finite and strictly nonnegative. Target and candidate
    rows must sum to one within `rtol=1e-7`, `atol=1e-8`. Inputs are not
    normalized or clipped.

    Every category with positive target mass must have positive mass in at
    least one candidate. The objective is evaluated exactly over categories;
    it uses no sampling or approximation. Only forward KL fitting is supported.
    """
    _ = validate_optimizer(optimizer)
    return categorical.fit_categorical_weights(target, candidates, optimizer=optimizer)

fit_gaussian_weights

fit_gaussian_weights(
    target: Gaussian | GaussianMixture,
    candidates: Sequence[Gaussian | GaussianMixture],
    *,
    optimizer: Optimizer,
    objective: FitObjective,
    candidate_selector: CandidateSelector | None = None,
) -> GaussianWeightFitResult

Fit weights for a mixture of fixed Gaussian-family candidate distributions.

Fits nonnegative weights w_i such that the weighted mixture

\[ q_{\mathbf{w}}(x)=\sum_{i=1}^{L}w_iq_i(x), \qquad w_i\geq0,\quad\sum_{i=1}^{L}w_i=1, \]

approximates target density \(p\) according to the selected objective. Here \(L\) counts candidate distributions, \(\mathbf{w}\) their fitted weights, and \(x\in\mathbb{R}^d\) one observation. A candidate \(q_i\) may itself contain several Gaussian components; its internal component probabilities are fixed.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty candidate sequence with the same feature dimension as target.

  • optimizer (Optimizer) –

    Explicit optimizer configuration.

  • objective (FitObjective) –

    Explicit fitting-objective configuration.

  • candidate_selector (CandidateSelector or None, default: None ) –

    Optional candidate selection before preparation. Initial optimizer vectors refer to retained candidates in selected order. Precomputed sampling batches refer to all original candidates.

Returns:

  • GaussianWeightFitResult –

    Result containing the fitted weights, combined mixture, final objective value, objective and optimizer configurations, and termination metadata. Weights remain aligned to the original candidates, with zeros for those rejected by selection. KL and Jensen-Shannon values are in nats; MomentMatching reports a squared raw-moment residual.

Source code in src/gmm_divergence/fitting/_api.py
def fit_gaussian_weights(
    target: Gaussian | GaussianMixture,
    candidates: Sequence[Gaussian | GaussianMixture],
    *,
    optimizer: Optimizer,
    objective: FitObjective,
    candidate_selector: CandidateSelector | None = None,
) -> GaussianWeightFitResult:
    r"""Fit weights for a mixture of fixed Gaussian-family candidate distributions.

    Fits nonnegative weights `w_i` such that the weighted mixture

    $$
    q_{\mathbf{w}}(x)=\sum_{i=1}^{L}w_iq_i(x),
    \qquad w_i\geq0,\quad\sum_{i=1}^{L}w_i=1,
    $$

    approximates target density $p$ according to the selected objective.
    Here $L$ counts candidate distributions, $\mathbf{w}$ their fitted weights,
    and $x\in\mathbb{R}^d$ one observation. A candidate $q_i$ may itself contain
    several Gaussian components; its internal component probabilities are fixed.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty candidate sequence with the same feature dimension as target.
    optimizer : Optimizer
        Explicit optimizer configuration.
    objective : FitObjective
        Explicit fitting-objective configuration.
    candidate_selector : CandidateSelector or None, default=None
        Optional candidate selection before preparation. Initial optimizer
        vectors refer to retained candidates in selected order. Precomputed
        sampling batches refer to all original candidates.

    Returns
    -------
    GaussianWeightFitResult
        Result containing the fitted weights, combined mixture, final objective
        value, objective and optimizer configurations, and termination metadata.
        Weights remain aligned to the original candidates, with zeros for those
        rejected by selection. KL and Jensen-Shannon values are in nats;
        MomentMatching reports a squared raw-moment residual.

    """
    _ = validate_optimizer(optimizer)
    prepared = prepare_gaussian_weight_fit(
        target, candidates, objective=objective, candidate_selector=candidate_selector
    )
    return prepared.fit(optimizer=optimizer)

prune_mixture

prune_mixture(
    mixture: GaussianMixture, *, min_weight: float = 0.0001
) -> GaussianMixture

Remove components below a threshold and normalize retained weights.

Parameters:

  • mixture (GaussianMixture) –

    Distribution to prune without modifying it.

  • min_weight (float, default: 1e-4 ) –

    Finite, nonnegative threshold. Components with weights equal to the threshold are retained.

Returns:

  • GaussianMixture –

    Retained components in their original order, with normalized weights and retained provenance rows.

Raises:

  • ValueError –

    If the threshold is invalid or no positive mass remains.

Source code in src/gmm_divergence/distributions/_combine.py
def prune_mixture(mixture: GaussianMixture, *, min_weight: float = 1e-4) -> GaussianMixture:
    """Remove components below a threshold and normalize retained weights.

    Parameters
    ----------
    mixture : GaussianMixture
        Distribution to prune without modifying it.
    min_weight : float, default=1e-4
        Finite, nonnegative threshold. Components with weights equal to the
        threshold are retained.

    Returns
    -------
    GaussianMixture
        Retained components in their original order, with normalized weights
        and retained provenance rows.

    Raises
    ------
    ValueError
        If the threshold is invalid or no positive mass remains.
    """
    _ = validate_nonnegative_finite(min_weight, name="min_weight")
    indices = np.flatnonzero(mixture.weights >= min_weight)
    if indices.size == 0:
        msg = "All components were pruned; decrease min_weight."
        raise ValueError(msg)
    return mixture.select_components(indices)

Results

CategoricalWeightFitResult dataclass

CategoricalWeightFitResult(
    *,
    weights: FloatArray,
    probabilities: FloatArray,
    optimizer: Optimizer,
    objective_value: float,
    converged: bool,
    n_iterations: int,
    message: str,
)

Categorical forward-KL fit with independently owned, read-only arrays.

converged instance-attribute

converged: bool

Whether the optimizer reported successful termination.

message instance-attribute

message: str

Optimizer termination explanation.

n_iterations instance-attribute

n_iterations: int

Number of optimizer iterations.

objective class-attribute instance-attribute

objective: Literal['forward_kl'] = field(default='forward_kl', init=False)

Always forward_kl; categorical fitting supports this objective only.

objective_value instance-attribute

objective_value: float

Exact forward KL from the target to fitted probabilities, in nats.

optimizer instance-attribute

optimizer: Optimizer

Optimizer configuration, including any initial conditions.

probabilities instance-attribute

probabilities: FloatArray

Weighted combination of candidate rows in original category order. Shape (n_categories,).

weights instance-attribute

weights: FloatArray

Simplex weights in original candidate-row order. Shape (n_candidates,).

DivergenceResult dataclass

DivergenceResult(
    *,
    value: float,
    divergence: str = "kl",
    estimator: KLEstimator | None = None,
    n_evaluations: int | None = None,
    monte_carlo: MonteCarloStatistics | None = None,
    terms: tuple[DivergenceResult, ...] = (),
)

A divergence in nats with estimator and evaluation metadata.

divergence class-attribute instance-attribute

divergence: str = 'kl'

Quantity computed: kl, categorical_kl, symmetric_kl, or jensen_shannon.

estimator class-attribute instance-attribute

estimator: KLEstimator | None = None

Configuration used for a directed Gaussian-family estimate. None for categorical and composite results; composites retain it on their terms.

monte_carlo class-attribute instance-attribute

monte_carlo: MonteCarloStatistics | None = None

Sampling diagnostics for a directed Monte Carlo estimate. Other methods and composites have no aggregate sampling-uncertainty record.

n_evaluations class-attribute instance-attribute

n_evaluations: int | None = None

Number of sample or deterministic integration points evaluated. None for methods without such counts, or composites with an uncounted term. Each point counts once, even though both densities are evaluated there.

n_samples property

n_samples: int | None

Monte Carlo observation counts, excluding deterministic points.

Composite results sum counts from their sampled terms. Returns None when no term reports Monte Carlo observations; repeated observations in different terms are counted separately.

terms class-attribute instance-attribute

terms: tuple[DivergenceResult, ...] = ()

Ordered directional results for composite quantities: forward then reverse for symmetric KL, p-to-midpoint then q-to-midpoint for JS.

value instance-attribute

value: float

Directed or composite divergence value. Estimates may be negative; categorical KL may be infinite when comparison support is missing.

GaussianWeightFitResult dataclass

GaussianWeightFitResult(
    *,
    weights: Weights,
    objective: FitObjective,
    optimizer: Optimizer,
    objective_value: float,
    mixture: GaussianMixture,
    converged: bool,
    n_iterations: int,
    message: str,
    active_candidate_indices: tuple[int, ...] = (),
)

Fitted candidate weights and a directly usable mixture with provenance.

active_candidate_indices class-attribute instance-attribute

active_candidate_indices: tuple[int, ...] = ()

Retained positions in their optimization order. Slice weights by these indices when constructing a warm start for the prepared problem.

converged instance-attribute

converged: bool

Whether the optimizer reported successful termination.

message instance-attribute

message: str

Optimizer termination explanation.

mixture instance-attribute

mixture: GaussianMixture

Combined fitted distribution. Its mapping identifies original candidate indices and component positions within those candidates.

n_iterations instance-attribute

n_iterations: int

Number of optimizer iterations.

objective instance-attribute

objective: FitObjective

Objective and sampling configuration used for preparation.

objective_value instance-attribute

objective_value: float

Final cached objective: KL or JS in nats, including target constants, or a squared raw-moment residual for MomentMatching.

optimizer instance-attribute

optimizer: Optimizer

Optimizer configuration, including any initial conditions.

weights instance-attribute

weights: Weights

Independent, read-only weights in original candidate order. Rejected candidates receive zero weight. Shape (n_candidates,).

candidate_weight_dict

candidate_weight_dict() -> dict[int, float]

Return weights keyed by original candidate index.

Returns:

  • dict –

    Candidate indices mapped to float weights, including zero weights. Insertion order follows candidate_weights(), descending by weight.

Source code in src/gmm_divergence/results.py
def candidate_weight_dict(self) -> dict[int, float]:
    """Return weights keyed by original candidate index.

    Returns
    -------
    dict
        Candidate indices mapped to float weights, including zero weights.
        Insertion order follows candidate_weights(), descending by weight.
    """
    return dict(self.candidate_weights())

candidate_weights

candidate_weights() -> list[tuple[int, float]]

List original candidate indices and weights in descending weight order.

Returns:

  • list of tuple –

    Index and weight pairs, including rejected candidates with zero weight. Ties preserve the original candidate order.

Source code in src/gmm_divergence/results.py
def candidate_weights(self) -> list[tuple[int, float]]:
    """List original candidate indices and weights in descending weight order.

    Returns
    -------
    list of tuple
        Index and weight pairs, including rejected candidates with zero
        weight. Ties preserve the original candidate order.
    """
    return sorted(enumerate(map(float, self.weights)), key=lambda item: -item[1])