Skip to content

Sampling API

Sampling configuration lives in gmm_divergence.sampling. These objects are used by Monte Carlo divergence estimators and sampled fitting objectives.

Distribution .sample(n_samples, rng=...) returns an array of shape (n_samples, n_features). Sampling specifications return immutable SampleBatch records with samples, optional normalized integration_weights, and optional component_ids. Batched specifications return a tuple of records in source order. Fitting requires equal observation counts across candidate batches.

An integer rng seed restarts a stream on each call; a numpy.random.Generator advances its state. Batched generated sampling uses one stream across sources.

With the notation conventions, observations are \(x_n\in\mathbb{R}^d\), \(n=1,\ldots,N\). A batch's integration weights satisfy \(a_n\geq0\) and \(\sum_{n=1}^{N}a_n=1\); an expectation is estimated by \(\sum_{n=1}^{N}a_n f(x_n)\) for an evaluated function \(f\). Omitting weights uses \(a_n=1/N\).

For stratified sampling from \(p\), observation \(x_{k,n}\) from component \(k\) has weight \(\pi_{p,k}/n_k\), where \(\pi_{p,k}\) is that component's probability and \(n_k\) its allocated draw count. Counts sum to \(N\), every positive-weight component has at least one draw, and zero-weight components have none. The stored component_ids use zero-based component positions.

import gmm_divergence as gd

components = [gd.Gaussian.univariate(-2), gd.Gaussian.univariate(2)]
target = gd.GaussianMixture.from_components(components, weights=[0.99, 0.01])
batch = gd.sampling.Stratified(n_samples=20, rng=0).sample(target)
assert batch.samples.shape == (20, 1)
assert batch.integration_weights is not None
assert batch.component_ids is not None
reused = gd.sampling.Samples(batch)
result = gd.kl_divergence(
    target, gd.Gaussian.univariate(), estimator=gd.divergence.MonteCarlo(sampling=reused)
)
assert result.n_samples == 20

Pass records to Samples and SampleBatches to preserve stratified integration metadata. Raw precomputed observations are interpreted as iid draws. Component IDs with integration weights describe fixed strata: weights must match source component mass divided by stratum count, and every positive-mass component must be represented. Arbitrary normalized integration weights without component IDs are supported, with uncertainty omitted.

Custom specifications implement SampleSpec.sample or BatchSampleSpec.sample_batches and return records, not arrays.

gmm_divergence.sampling

Public sampling records and specifications.

Draw dataclass

Draw(*, n_samples: int = 10000, rng: Generator | int | None = None)

Draw fresh, independent observations from each source distribution.

Parameters:

  • n_samples (int, default: 10000 ) –

    Positive number of observations per distribution.

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

    Random source. Integer seeds restart the stream on each method call; generators advance their state. None uses fresh entropy. Batch sampling uses one shared stream across sources within each call.

sample

sample(distribution: GaussianDistribution) -> SampleBatch

Draw an independent, equally weighted batch from the source.

Parameters:

Returns:

  • SampleBatch –

    New float64 observations with no integration weights or component IDs.

Source code in src/gmm_divergence/_core/_sampling.py
def sample(self, distribution: GaussianDistribution) -> SampleBatch:
    """Draw an independent, equally weighted batch from the source.

    Parameters
    ----------
    distribution : Gaussian or GaussianMixture
        Source distribution with the required feature dimensions.

    Returns
    -------
    SampleBatch
        New float64 observations with no integration weights or component IDs.
    """
    _validate_distribution(distribution)
    return SampleBatch(distribution.sample(self.n_samples, rng=self.rng))

sample_batches

sample_batches(
    distributions: Sequence[GaussianDistribution],
) -> tuple[SampleBatch, ...]

Draw independent batches using one shared random stream.

Parameters:

  • distributions (sequence of Gaussian or GaussianMixture) –

    Nonempty sequence of source distributions in the desired batch order.

Returns:

  • tuple of SampleBatch –

    One batch per source in input order, each containing n_samples observations. A shared generator advances across sources within this call.

Source code in src/gmm_divergence/_core/_sampling.py
def sample_batches(
    self, distributions: Sequence[GaussianDistribution]
) -> tuple[SampleBatch, ...]:
    """Draw independent batches using one shared random stream.

    Parameters
    ----------
    distributions : sequence of Gaussian or GaussianMixture
        Nonempty sequence of source distributions in the desired batch order.

    Returns
    -------
    tuple of SampleBatch
        One batch per source in input order, each containing n_samples observations.
        A shared generator advances across sources within this call.
    """
    _validate_distributions(distributions)
    rng = np.random.default_rng(self.rng)
    return tuple(SampleBatch(d.sample(self.n_samples, rng=rng)) for d in distributions)

Stratified dataclass

Stratified(*, n_samples: int = 10000, rng: Generator | int | None = None)

Draw fixed component allocations while preserving mixture integration mass.

Parameters:

  • n_samples (int, default: 10000 ) –

    Positive number of observations per distribution. Must allow at least one draw for every positive-weight component of each source.

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

    Random source. Integer seeds restart the stream on each method call; generators advance their state. Batch sampling shares one stream.

Notes

Each observation from component k has integration weight weights[k] / n_k, where n_k is its allocated count. Batches also carry component IDs. Counts sum to n_samples; zero-weight components receive no draws. A Gaussian is treated as a one-component mixture. Observations are grouped by component.

sample

sample(distribution: GaussianDistribution) -> SampleBatch

Draw a component-stratified batch from the source.

Parameters:

Returns:

  • SampleBatch –

    New observations with normalized integration weights and component IDs.

Source code in src/gmm_divergence/_core/_sampling.py
def sample(self, distribution: GaussianDistribution) -> SampleBatch:
    """Draw a component-stratified batch from the source.

    Parameters
    ----------
    distribution : Gaussian or GaussianMixture
        Source distribution with the required feature dimensions.

    Returns
    -------
    SampleBatch
        New observations with normalized integration weights and component IDs.
    """
    _validate_distribution(distribution)
    return stratified_mixture_samples(distribution, self)

sample_batches

sample_batches(
    distributions: Sequence[GaussianDistribution],
) -> tuple[SampleBatch, ...]

Draw stratified batches using one shared random stream.

Parameters:

  • distributions (sequence of Gaussian or GaussianMixture) –

    Nonempty sequence of source distributions in the desired batch order.

Returns:

  • tuple of SampleBatch –

    One batch per source in input order, each containing n_samples observations. A shared generator advances across sources within this call.

Source code in src/gmm_divergence/_core/_sampling.py
def sample_batches(
    self, distributions: Sequence[GaussianDistribution]
) -> tuple[SampleBatch, ...]:
    """Draw stratified batches using one shared random stream.

    Parameters
    ----------
    distributions : sequence of Gaussian or GaussianMixture
        Nonempty sequence of source distributions in the desired batch order.

    Returns
    -------
    tuple of SampleBatch
        One batch per source in input order, each containing n_samples observations.
        A shared generator advances across sources within this call.
    """
    _validate_distributions(distributions)
    rng = np.random.default_rng(self.rng)
    return tuple(stratified_mixture_samples(d, self, rng=rng) for d in distributions)

Samples dataclass

Samples(samples: SampleBatch | ArrayLike)

Reuse observations from a single source distribution without drawing again.

Parameters:

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

    Nonempty, finite source observations. Arrays are copied into an immutable batch and treated as equally weighted observations. A SampleBatch is reused with its integration weights and component IDs intact.

Notes

Feature dimensions and component metadata are checked against the source when sampling. The caller must ensure observations originate from that source; this cannot be inferred from their values.

Source code in src/gmm_divergence/_core/_sampling.py
def __init__(self, samples: SampleBatch | npt.ArrayLike) -> None:
    batch = samples if isinstance(samples, SampleBatch) else SampleBatch(samples)
    object.__setattr__(self, "samples", batch)

sample

sample(distribution: GaussianDistribution) -> SampleBatch

Validate and return the stored batch without drawing samples.

Parameters:

Returns:

  • SampleBatch –

    Stored batch with its integration weights and component IDs unchanged.

Source code in src/gmm_divergence/_core/_sampling.py
def sample(self, distribution: GaussianDistribution) -> SampleBatch:
    """Validate and return the stored batch without drawing samples.

    Parameters
    ----------
    distribution : Gaussian or GaussianMixture
        Source distribution with the required feature dimensions.

    Returns
    -------
    SampleBatch
        Stored batch with its integration weights and component IDs unchanged.
    """
    batch = self.samples
    return validate_sample_batch(distribution, batch)

SampleBatches dataclass

SampleBatches(samples: Sequence[SampleBatch] | ArrayLike)

Reuse one precomputed batch per source distribution.

Parameters:

  • samples (sequence of SampleBatch or array-like) –

    Nonempty sequence of immutable batches, or finite observations with shape (n_distributions, n_samples, n_features). Arrays are copied; records preserve their integration weights and component IDs.

Notes

For fitting, supply one batch per original candidate before filtering or reordering. Batches must have equal sample counts and matching feature dimensions. The caller is responsible for sampling from the correct sources.

Source code in src/gmm_divergence/_core/_sampling.py
def __init__(self, samples: Sequence[SampleBatch] | npt.ArrayLike) -> None:
    values = samples
    if isinstance(values, Sequence) and all(isinstance(batch, SampleBatch) for batch in values):
        batches = tuple(values)
    else:
        array = np.asarray(values, dtype=np.float64)
        if array.ndim != 3 or 0 in array.shape:
            msg = "samples must have shape (n_distributions, n_samples, n_features)."
            raise ValueError(msg)
        batches = tuple(SampleBatch(batch) for batch in array)
    if not batches:
        msg = "samples must contain at least one batch."
        raise ValueError(msg)
    object.__setattr__(self, "samples", batches)

sample_batches

sample_batches(
    distributions: Sequence[GaussianDistribution],
) -> tuple[SampleBatch, ...]

Validate and return precomputed batches without drawing new samples.

Parameters:

  • distributions (sequence of Gaussian or GaussianMixture) –

    Original sources in the same order as the stored batches.

Returns:

  • tuple of SampleBatch –

    Stored batches with source dimensions and component metadata checked.

Source code in src/gmm_divergence/_core/_sampling.py
def sample_batches(
    self, distributions: Sequence[GaussianDistribution]
) -> tuple[SampleBatch, ...]:
    """Validate and return precomputed batches without drawing new samples.

    Parameters
    ----------
    distributions : sequence of Gaussian or GaussianMixture
        Original sources in the same order as the stored batches.

    Returns
    -------
    tuple of SampleBatch
        Stored batches with source dimensions and component metadata checked.
    """
    _validate_distributions(distributions)
    batches = self.samples
    if len(batches) != len(distributions):
        msg = "samples must contain one batch per original candidate distribution."
        raise ValueError(msg)
    return tuple(starmap(validate_sample_batch, zip(distributions, batches, strict=True)))

SampleBatch dataclass

SampleBatch(
    samples: ArrayLike,
    *,
    integration_weights: ArrayLike | None = None,
    component_ids: ArrayLike | None = None,
)

Immutable observations with optional integration weights and strata.

Parameters:

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

    Nonempty, finite observations, copied into a read-only float64 array.

  • integration_weights (array-like, shape (n_samples,), or None, default: None ) –

    Finite, nonnegative weights summing to one within rtol=1e-7, atol=1e-8. Values are copied without normalization. None requests an ordinary mean.

  • component_ids (array-like, shape (n_samples,), or None, default: None ) –

    Nonnegative integer component positions, copied into a read-only intp array. Source bounds are checked when the batch is used.

Notes

When both weights and component IDs are provided, reuse validates that each positive-weight source component is represented and each observation's weight equals its component mass divided by the number of observations in its stratum.

Source code in src/gmm_divergence/_core/_sampling.py
def __init__(
    self,
    samples: npt.ArrayLike,
    *,
    integration_weights: npt.ArrayLike | None = None,
    component_ids: npt.ArrayLike | None = None,
) -> None:
    points = readonly_copy(samples, dtype=np.float64)
    if points.ndim != 2 or 0 in points.shape or not np.all(np.isfinite(points)):
        msg = "samples must be a nonempty finite array of shape (n_samples, n_features)."
        raise ValueError(msg)
    weights = None
    if integration_weights is not None:
        weights = as_weights(
            integration_weights,
            expected_length=len(points),
            normalize=False,
            name="integration_weights",
        )
        if not np.isclose(weights.sum(), 1.0, rtol=1e-7, atol=1e-8):
            msg = "integration_weights must sum to one."
            raise ValueError(msg)
    ids = None
    if component_ids is not None:
        array = np.asarray(component_ids)
        if array.ndim != 1 or len(array) != len(points):
            msg = "component_ids must have one entry per sample."
            raise ValueError(msg)
        if array.dtype.kind not in "iu":
            msg = "component_ids must contain integers."
            raise TypeError(msg)
        if np.any(array < 0) or np.any(array > np.iinfo(np.intp).max):
            msg = "component_ids must contain nonnegative component positions."
            raise IndexError(msg)
        ids = readonly_copy(array, dtype=np.intp)
    object.__setattr__(self, "samples", points)
    object.__setattr__(self, "integration_weights", weights)
    object.__setattr__(self, "component_ids", ids)

SampleSpec

Bases: Protocol

Protocol for a sample source returning observations and integration metadata.

sample

sample(distribution: GaussianDistribution) -> SampleBatch

Return a batch originating from the supplied distribution.

Parameters:

  • distribution (Gaussian or GaussianMixture) –

    Source distribution; any precomputed observations must come from it.

Returns:

  • SampleBatch –

    Finite observations with matching feature dimensions and optional integration weights and source component IDs.

Source code in src/gmm_divergence/_core/_sampling.py
def sample(self, distribution: GaussianDistribution) -> SampleBatch:
    """Return a batch originating from the supplied distribution.

    Parameters
    ----------
    distribution : Gaussian or GaussianMixture
        Source distribution; any precomputed observations must come from it.

    Returns
    -------
    SampleBatch
        Finite observations with matching feature dimensions and optional
        integration weights and source component IDs.
    """
    ...

BatchSampleSpec

Bases: Protocol

Protocol for one sample batch per source distribution.

sample_batches

sample_batches(
    distributions: Sequence[GaussianDistribution],
) -> tuple[SampleBatch, ...]

Return one batch per distribution, preserving input order.

Parameters:

  • distributions (sequence of Gaussian or GaussianMixture) –

    Nonempty sequence of source distributions.

Returns:

  • tuple of SampleBatch –

    One batch per source. Fitting requires equal sample counts and feature dimensions across batches.

Source code in src/gmm_divergence/_core/_sampling.py
def sample_batches(
    self, distributions: Sequence[GaussianDistribution]
) -> tuple[SampleBatch, ...]:
    """Return one batch per distribution, preserving input order.

    Parameters
    ----------
    distributions : sequence of Gaussian or GaussianMixture
        Nonempty sequence of source distributions.

    Returns
    -------
    tuple of SampleBatch
        One batch per source. Fitting requires equal sample counts and
        feature dimensions across batches.
    """
    ...