Skip to content

Measure Algebra

These combinators build measures from measures: Mixture, Restrict, Pushforward, PointMass, Independent, and Normalize, which back the operator families of the DSL. Restricting a probability measure to an event of probability 0.2 leaves total mass 0.2, and dividing by 0.2 gives the conditional distribution (Bernardo and Smith, 1994). Each combinator states whether it keeps that mass or normalizes it, and normalize_at_boundary renormalizes a subprobability measure where it is sampled or scored.

Independent(base, reinterpreted_batch_ndims=0) is the identity case: it preserves every base batch and intrinsic event axis, raw mass, and interval query. Positive counts reinterpret that many trailing batch axes as one event and multiply their masses. Counts must be nonnegative integers no larger than the base batch rank. The identity case does not reduce the batch axes.

An intrinsic base event follows the reinterpreted batch axes. For a base with batch shape (2, 3) and event shape (4,), a count of one gives batch (2,) and event (3, 4); zero retains (2, 3) and (4,). Boolean and fractional counts are invalid. Native construction and checked source use the same axis-count validation; source examples show how typed headers distinguish outer rows from base batch axes.

import torch
from quivers.continuous.measure import Independent, Normalize, Restrict

base = torch.distributions.Normal(torch.zeros(2, 3), torch.ones(2, 3))
product = Independent(Restrict(base, -1.0, 1.0), 1)
assert product.batch_shape == torch.Size((2,))
assert product.event_shape == torch.Size((3,))
normalized = Normalize(product)
point = torch.zeros(2, 3)
expected = base.log_prob(point).sum(-1) - product.log_normalizer()
torch.testing.assert_close(normalized.log_prob(point), expected)

This restriction retains its raw coordinate masses until Normalize divides by their product. Reinterpreting batch axes does not normalize the base.

Raw masses and interval endpoints

log_interval_mass(low, high, lower_closed=..., upper_closed=...) integrates the retained measure over the requested interval. Both endpoints are included by default; either flag may be false, including for discrete or mixed laws. An interval with equal endpoints contains only its atom when both flags are true. None leaves that side unbounded.

The four log-tail methods use this same operation:

Method Event
log_cdf(x) \((-\infty,x]\)
log_cdf_left(x) \((-\infty,x)\)
log_survival_function(x) \((x,\infty)\)
log_survival_function_left(x) \([x,\infty)\)

These methods return raw mass. Thus cdf(x) can exceed one for an unnormalized measure; Normalize(base).cdf(x) gives its probability CDF. Restrict retains intersection mass, and Normalize divides by the retained total mass once. A mixture's sampling probability for component \(j\) is proportional to its raw weight times its total mass, so a restricted component is selected according to its remaining mass.

import torch
from quivers.continuous.measure import Mixture, Normalize, PointMass, Restrict

half = Restrict(torch.distributions.Uniform(0.0, 1.0), 0.0, 0.5)
raw = Mixture(torch.tensor([2.0, 3.0]), [half, PointMass(torch.tensor(0.0))])
probability = Normalize(raw)
assert abs(raw.log_normalizer().exp().item() - 4.0) < 1e-6
assert abs(probability.cdf(torch.tensor(0.0)).item() - 0.75) < 1e-6
open_lower = probability.log_interval_mass(0.0, 0.25, lower_closed=False).exp()
assert abs(open_lower.item() - 0.125) < 1e-6

Atoms and density references

A scalar mixture combines component densities against one common reference. At any retained atom, log_prob includes atomic masses alone; an atomless component's continuous density does not add probability to that point. Away from the atom carrier, continuous component densities contribute as usual. Integer-valued scalar laws use counting measure on the integers, including integer locations where a particular component assigns zero mass.

atom_reference(value) identifies the retained atomic carrier, while log_atom_mass(value) reads its raw mass. Restriction can remove an atom's mass without changing the base carrier, and normalization rescales the mass. Coupled mixed vector laws need a joint stratum reference; composition that lacks this information fails explicitly.

Censoring and truncation use these interval masses for different purposes. An interval-censored observation contributes the event's raw mass. A truncated response instead uses the normalized restriction as its whole response law. The Censored distribution is a third operation: it clamps sampled values to its endpoints and retains the resulting endpoint atoms.

Restriction masks excluded values before invoking a base density. This retains zero mass outside either the interval or a parameter-dependent base support, without evaluating an invalid logarithm in an inactive branch. Independent event coordinates reduce the mask to their event's batch axes. Conditional families.Truncated reuses Normalize(Restrict(...)) for its coordinate laws; both interfaces share the rejection loop while retaining their sampling policy and attempt budget. Normal coordinates retain their specialized inverse sampler.

Batch selection and transformed event shapes

Measure.select_batch(active, output_shape=...) selects active batch cells while retaining each event intact. Mixture components, restrictions, and normalizers delegate through this operation; a vector response's component axis is not another batch axis.

A pushforward obtains its output event shape from the bijector's forward_shape; inversion uses inverse_shape. Its jacobian_event_dim states which trailing event coordinates the Jacobian already reduces. Composition reduces any remaining event coordinates exactly once. Thus a shape-changing stick-breaking map retains its simplex event axis, and a composed vector map does not duplicate or omit the change-of-variables term. Parameterized bijectors implement select_batch alongside the measure so masked evaluation uses the corresponding parameters.

measure

Sub-Giry measures and their primitive transformations.

A Measure is an unnormalized positive measure on a Borel space. Probability measures have total mass one; restrictions and likelihood scores may produce sub-probability measures. The runtime tracks total mass as a log normalizer and normalizes at sample or observation boundaries.

The module provides point masses, restriction, pushforward through a bijector, finite mixtures, event-dimension declarations with Independent, and normalization of positive-mass sub-measures.

Measure

Bases: Distribution, ABC

Abstract base for sub-Giry monad values.

The runtime tracks each Measure as a sub-distribution: it has a log_prob returning the unnormalised log-density and a log_normalizer() returning the log of the total mass. For probability measures (mass one), log_normalizer() returns zero by definition. For sub-measures from Restrict or Mixture with unnormalised weights, log_normalizer() carries the residual mass symbolically until the next Normalize or sample / observe boundary.

log_prob_normalized(value) is a derived helper returning log_prob(value) - log_normalizer() so consumers that want the probability-measure log-density can ask for it explicitly.

log_normalizer abstractmethod

log_normalizer() -> Tensor

Log of the total mass of this measure. For probability measures, zero. For sub-measures, the symbolic normaliser the lazy algebra carries through composition.

Source code in src/quivers/continuous/measure.py
@abstractmethod
def log_normalizer(self) -> Tensor:
    """Log of the total mass of this measure. For probability
    measures, zero. For sub-measures, the symbolic normaliser
    the lazy algebra carries through composition.
    """

select_batch

select_batch(active: Tensor, *, output_shape=None) -> Distribution

Reconstruct selected rows of the compositional measure algebra.

PARAMETER DESCRIPTION
active

Boolean selection over the measure's broadcast batch.

TYPE: Tensor

output_shape

Optional selected batch layout, retaining reinterpreted event axes.

TYPE: Size or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

The same measure construction on the selected parameter rows.

RAISES DESCRIPTION
NotImplementedError

If a custom measure supplies no batch reconstruction rule.

Source code in src/quivers/continuous/measure.py
def select_batch(self, active: Tensor, *, output_shape=None) -> Distribution:
    """Reconstruct selected rows of the compositional measure algebra.

    Parameters
    ----------
    active : Tensor
        Boolean selection over the measure's broadcast batch.
    output_shape : torch.Size or None
        Optional selected batch layout, retaining reinterpreted event axes.

    Returns
    -------
    Distribution
        The same measure construction on the selected parameter rows.

    Raises
    ------
    NotImplementedError
        If a custom measure supplies no batch reconstruction rule.
    """
    from quivers.continuous._batch_selection import select_batch, select_parameter

    def parameter(value, rank=0):
        """Select parameter batch axes while retaining intrinsic axes."""
        if not isinstance(value, Tensor):
            return value
        return select_parameter(
            value, self.batch_shape, rank, active, output_shape=output_shape
        )

    def base(distribution):
        """Broadcast a component before selecting the common batch rows."""
        expanded = distribution.expand(self.batch_shape)
        return select_batch(expanded, active, output_shape=output_shape)

    if isinstance(self, PointMass):
        return PointMass(parameter(self.value))
    if isinstance(self, Restrict):
        return Restrict(
            base(self.base),
            parameter(self.low),
            parameter(self.high),
            lower_closed=parameter(self.lower_closed),
            upper_closed=parameter(self.upper_closed),
        )
    if isinstance(self, Normalize):
        return Normalize(base(self.base))
    if isinstance(self, Pushforward):
        transform = self.bijector.select_batch(
            self.batch_shape,
            active,
            event_shape=self.base.event_shape,
            output_shape=output_shape,
        )
        return Pushforward(base(self.base), transform)
    if isinstance(self, Mixture):
        return Mixture(
            parameter(self.weights, 1), [base(c) for c in self.components]
        )
    if isinstance(self, Independent):
        selected = select_batch(self._inner, active, output_shape=output_shape)
        return Independent(selected.base_dist, self.reinterpreted_batch_ndims)
    raise NotImplementedError(
        f"{type(self).__name__} has no batch reconstruction rule"
    )

log_prob_normalized

log_prob_normalized(value: Tensor) -> Tensor

Log-density of the renormalised probability measure.

PARAMETER DESCRIPTION
value

Evaluation points, broadcast against the distribution batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log density after subtracting the raw total log mass.

Source code in src/quivers/continuous/measure.py
def log_prob_normalized(self, value: Tensor) -> Tensor:
    """Log-density of the renormalised probability measure.

    Parameters
    ----------
    value : Tensor
        Evaluation points, broadcast against the distribution batch.

    Returns
    -------
    Tensor
        Log density after subtracting the raw total log mass."""
    return self.log_prob(value) - self.log_normalizer()

log_interval_mass

log_interval_mass(low, high, *, lower_closed=True, upper_closed=True)

Read a raw event mass supplied by the concrete measure algebra.

PARAMETER DESCRIPTION
low

Optional scalar bounds.

TYPE: Tensor or float or None

high

Optional scalar bounds.

TYPE: Tensor or float or None

lower_closed

Whether each endpoint belongs to the event.

TYPE: bool or Tensor DEFAULT: True

upper_closed

Whether each endpoint belongs to the event.

TYPE: bool or Tensor DEFAULT: True

RETURNS DESCRIPTION
Tensor

Raw log event mass.

RAISES DESCRIPTION
NotImplementedError

If a custom measure has no interval integration capability.

Source code in src/quivers/continuous/measure.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Read a raw event mass supplied by the concrete measure algebra.

    Parameters
    ----------
    low, high : Tensor or float or None
        Optional scalar bounds.
    lower_closed, upper_closed : bool or Tensor
        Whether each endpoint belongs to the event.

    Returns
    -------
    Tensor
        Raw log event mass.

    Raises
    ------
    NotImplementedError
        If a custom measure has no interval integration capability.
    """
    raise NotImplementedError(
        f"{type(self).__name__} does not implement interval event masses"
    )

log_cdf

log_cdf(value: Tensor) -> Tensor

Read raw log mass on the closed lower half-line.

PARAMETER DESCRIPTION
value

Scalar cutoffs, broadcast against the measure batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log mass on (-inf,value]; a normalized measure has an ordinary log CDF.

Source code in src/quivers/continuous/measure.py
def log_cdf(self, value: Tensor) -> Tensor:
    """Read raw log mass on the closed lower half-line.

    Parameters
    ----------
    value : Tensor
        Scalar cutoffs, broadcast against the measure batch.

    Returns
    -------
    Tensor
        Log mass on ``(-inf,value]``; a normalized measure has an ordinary log CDF.
    """
    return self.log_interval_mass(None, value)

log_survival_function

log_survival_function(value: Tensor) -> Tensor

Read raw log mass on the open upper half-line.

PARAMETER DESCRIPTION
value

Scalar cutoffs, broadcast against the measure batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log mass on (value,inf).

Source code in src/quivers/continuous/measure.py
def log_survival_function(self, value: Tensor) -> Tensor:
    """Read raw log mass on the open upper half-line.

    Parameters
    ----------
    value : Tensor
        Scalar cutoffs, broadcast against the measure batch.

    Returns
    -------
    Tensor
        Log mass on ``(value,inf)``.
    """
    return self.log_interval_mass(value, None, lower_closed=False)

log_cdf_left

log_cdf_left(value: Tensor) -> Tensor

Read raw log mass strictly below a cutoff.

PARAMETER DESCRIPTION
value

Scalar cutoffs, broadcast against the measure batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log mass on (-inf,value).

Source code in src/quivers/continuous/measure.py
def log_cdf_left(self, value: Tensor) -> Tensor:
    """Read raw log mass strictly below a cutoff.

    Parameters
    ----------
    value : Tensor
        Scalar cutoffs, broadcast against the measure batch.

    Returns
    -------
    Tensor
        Log mass on ``(-inf,value)``.
    """
    return self.log_interval_mass(None, value, upper_closed=False)

log_survival_function_left

log_survival_function_left(value: Tensor) -> Tensor

Read raw log mass at or above a cutoff.

PARAMETER DESCRIPTION
value

Scalar cutoffs, broadcast against the measure batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log mass on [value,inf).

Source code in src/quivers/continuous/measure.py
def log_survival_function_left(self, value: Tensor) -> Tensor:
    """Read raw log mass at or above a cutoff.

    Parameters
    ----------
    value : Tensor
        Scalar cutoffs, broadcast against the measure batch.

    Returns
    -------
    Tensor
        Log mass on ``[value,inf)``.
    """
    return self.log_interval_mass(value, None)

cdf

cdf(value: Tensor) -> Tensor

Read raw lower-half-line mass from the same interval operation.

PARAMETER DESCRIPTION
value

Scalar cutoffs, broadcast against the measure batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

CDF for a normalized measure; raw cumulative mass otherwise.

Source code in src/quivers/continuous/measure.py
def cdf(self, value: Tensor) -> Tensor:
    """Read raw lower-half-line mass from the same interval operation.

    Parameters
    ----------
    value : Tensor
        Scalar cutoffs, broadcast against the measure batch.

    Returns
    -------
    Tensor
        CDF for a normalized measure; raw cumulative mass otherwise.
    """
    return self.log_cdf(value).exp()

PointMass

PointMass(value: Tensor | float, validate_args: bool | None = None)

Bases: Measure

Dirac measure at a deterministic value.

The unit \(\eta\) of the Giry monad: PointMass(x) is the measure that places mass one on the singleton \(\{x\}\). log_prob(y) is zero when y == value and \(-\infty\) otherwise.

In a Mixture alongside a non-degenerate component, PointMass is the structural-zero spike that yields zero-inflation and hurdle factorisations.

PARAMETER DESCRIPTION
value

Retained location of the atom.

TYPE: Tensor or float

validate_args

Optional Torch argument-validation policy.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/measure.py
def __init__(
    self,
    value: Tensor | float,
    validate_args: bool | None = None,
) -> None:
    self.value = torch.as_tensor(value)
    super().__init__(
        batch_shape=self.value.shape,
        event_shape=torch.Size(()),
        validate_args=validate_args,
    )

mean property

mean: Tensor

Expected response under the probability law.

RETURNS DESCRIPTION
Tensor

Expected response under the probability law.

variance property

variance: Tensor

Response variance under the probability law.

RETURNS DESCRIPTION
Tensor

Response variance under the probability law.

atom_reference

atom_reference(value: Tensor) -> Tensor

Identify the retained Dirac carrier independently of scalar dtype.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each query equals the retained atom.

Source code in src/quivers/continuous/measure.py
def atom_reference(self, value: Tensor) -> Tensor:
    """Identify the retained Dirac carrier independently of scalar dtype.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Whether each query equals the retained atom.
    """
    point = torch.as_tensor(value, dtype=torch.float64, device=self.value.device)
    return point == self.value.double()

log_atom_mass

log_atom_mass(value: Tensor) -> Tensor

Read singleton mass under the same Dirac carrier.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Zero at the atom and negative infinity elsewhere.

Source code in src/quivers/continuous/measure.py
def log_atom_mass(self, value: Tensor) -> Tensor:
    """Read singleton mass under the same Dirac carrier.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Zero at the atom and negative infinity elsewhere.
    """
    carrier = self.atom_reference(value)
    return torch.where(
        carrier, torch.zeros_like(carrier, dtype=_reference(self).dtype), -torch.inf
    )

support

support() -> Constraint

Constraint describing valid response values.

RETURNS DESCRIPTION
Constraint

Constraint describing valid response values.

Source code in src/quivers/continuous/measure.py
@_constraints.dependent_property
def support(self) -> _constraints.Constraint:
    """Constraint describing valid response values.

    Returns
    -------
    _constraints.Constraint
        Constraint describing valid response values."""
    return _constraints.real

log_normalizer

log_normalizer() -> Tensor

Log of the raw total mass, one value per batch entry.

RETURNS DESCRIPTION
Tensor

Log of the raw total mass, one value per batch entry.

Source code in src/quivers/continuous/measure.py
def log_normalizer(self) -> Tensor:
    """Log of the raw total mass, one value per batch entry.

    Returns
    -------
    Tensor
        Log of the raw total mass, one value per batch entry."""
    return torch.zeros_like(_reference(self))

expand

expand(batch_shape, _instance=None)

Broadcast the retained atom over a new batch shape.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch shape.

TYPE: object

_instance

Unused Torch expansion instance.

TYPE: object DEFAULT: None

RETURNS DESCRIPTION
object

Distribution with the requested batch shape and retained construction.

Source code in src/quivers/continuous/measure.py
def expand(self, batch_shape, _instance=None):
    """Broadcast the retained atom over a new batch shape.

    Parameters
    ----------
    batch_shape : object
        Requested broadcast batch shape.
    _instance : object
        Unused Torch expansion instance.

    Returns
    -------
    object
        Distribution with the requested batch shape and retained construction."""
    return PointMass(self.value.expand(batch_shape))

log_interval_mass

log_interval_mass(low, high, *, lower_closed=True, upper_closed=True)

Keep the atom exactly when both interval bounds admit its value.

PARAMETER DESCRIPTION
low

Optional event bounds.

TYPE: Tensor or float or None

high

Optional event bounds.

TYPE: Tensor or float or None

lower_closed

Endpoint membership.

TYPE: bool or Tensor DEFAULT: True

upper_closed

Endpoint membership.

TYPE: bool or Tensor DEFAULT: True

RETURNS DESCRIPTION
Tensor

Zero at included atoms and negative infinity elsewhere.

RAISES DESCRIPTION
ValueError

If an endpoint is NaN.

Source code in src/quivers/continuous/measure.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Keep the atom exactly when both interval bounds admit its value.

    Parameters
    ----------
    low, high : Tensor or float or None
        Optional event bounds.
    lower_closed, upper_closed : bool or Tensor
        Endpoint membership.

    Returns
    -------
    Tensor
        Zero at included atoms and negative infinity elsewhere.

    Raises
    ------
    ValueError
        If an endpoint is NaN.
    """
    low = -torch.inf if low is None else low
    high = torch.inf if high is None else high
    low, high = torch.broadcast_tensors(
        torch.as_tensor(low, device=self.value.device, dtype=torch.float64),
        torch.as_tensor(high, device=self.value.device, dtype=torch.float64),
    )
    demand(
        ~(low.isnan() | high.isnan()),
        lambda: ValueError("point-mass interval endpoints must not be NaN"),
    )
    lower_closed = torch.as_tensor(
        _closed_flag(lower_closed, "lower_closed"), device=self.value.device
    )
    upper_closed = torch.as_tensor(
        _closed_flag(upper_closed, "upper_closed"), device=self.value.device
    )
    atom = self.value.double()
    inside = ((atom > low) | ((atom == low) & lower_closed)) & (
        (atom < high) | ((atom == high) & upper_closed)
    )
    return torch.where(
        inside, torch.zeros_like(inside, dtype=_reference(self).dtype), -torch.inf
    )

icdf

icdf(value: Tensor) -> Tensor

Return the atom at every valid probability.

PARAMETER DESCRIPTION
value

Evaluation points, broadcast against the distribution batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Response quantiles at the requested probabilities.

RAISES DESCRIPTION
ValueError

If a probability is NaN or lies outside [0,1].

Source code in src/quivers/continuous/measure.py
def icdf(self, value: Tensor) -> Tensor:
    """Return the atom at every valid probability.

    Parameters
    ----------
    value : Tensor
        Evaluation points, broadcast against the distribution batch.

    Returns
    -------
    Tensor
        Response quantiles at the requested probabilities.

    Raises
    ------
    ValueError
        If a probability is NaN or lies outside [0,1]."""
    point = torch.as_tensor(value, device=self.value.device)
    if not bool(((point >= 0) & (point <= 1)).all()):
        raise ValueError("point-mass quantiles require probabilities in [0,1]")
    return self.value.expand(torch.broadcast_shapes(point.shape, self.batch_shape))

log_prob

log_prob(value: Tensor) -> Tensor

The log mass at a point: zero at the atom, -inf elsewhere.

The result takes the floating dtype of value (the default dtype for an integer or Boolean value), so a double-precision mixture is not rounded to single precision by its atom's term.

PARAMETER DESCRIPTION
value

The points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The log masses.

Source code in src/quivers/continuous/measure.py
def log_prob(self, value: Tensor) -> Tensor:
    """The log mass at a point: zero at the atom, ``-inf`` elsewhere.

    The result takes the floating dtype of ``value`` (the default
    dtype for an integer or Boolean value), so a double-precision
    mixture is not rounded to single precision by its atom's term.

    Parameters
    ----------
    value : Tensor
        The points.

    Returns
    -------
    Tensor
        The log masses.
    """
    value_b = torch.as_tensor(value)
    match = value_b == self.value
    if match.dtype != torch.bool:
        match = match.bool()
    dtype = (
        value_b.dtype if value_b.is_floating_point() else torch.get_default_dtype()
    )
    out = torch.full(
        torch.broadcast_shapes(value_b.shape, self.value.shape),
        _NEG_INF,
        dtype=dtype,
        device=match.device,
    )
    out = torch.where(match, torch.zeros_like(out), out)
    return out

sample

sample(sample_shape: Size = Size()) -> Tensor

Draws from the normalized law with leading sample dimensions.

PARAMETER DESCRIPTION
sample_shape

Leading independent sampling dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws from the normalized law with leading sample dimensions.

Source code in src/quivers/continuous/measure.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draws from the normalized law with leading sample dimensions.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading independent sampling dimensions.

    Returns
    -------
    Tensor
        Draws from the normalized law with leading sample dimensions."""
    shape = torch.Size(sample_shape) + self.batch_shape
    return self.value.expand(shape) if shape else self.value

Restrict

Restrict(base: Distribution, low: Tensor | float | None = None, high: Tensor | float | None = None, validate_args: bool | None = None, *, lower_closed: bool | Tensor = True, upper_closed: bool | Tensor = True)

Bases: Measure

Restriction of a base distribution to a sub-interval.

Restricts base to the interval [low, high] (with low or high set to \(\pm\infty\) for one-sided restrictions). The log-density is base.log_prob(value) inside the interval and \(-\infty\) outside; the symbolic log-normaliser is the log of the base measure's mass on [low, high].

The compiler does not renormalise eagerly; the sub-measure propagates through Mixture, Pushforward, and other operators until a Normalize or sample / observe boundary collapses it. This is the discipline that makes the algebra close, per Di Lavore-Roman-Sobocinski 2025.

Normal interval masses use log-CDF differences with tail reflection. Other continuous bases use their CDF difference, and discrete bases use interval probabilities that include both endpoints.

PARAMETER DESCRIPTION
base

Underlying distribution or raw measure.

TYPE: Distribution

low

Optional interval endpoints; omitted sides are unbounded.

TYPE: Tensor or float or None DEFAULT: None

high

Optional interval endpoints; omitted sides are unbounded.

TYPE: Tensor or float or None DEFAULT: None

validate_args

Optional Torch argument-validation policy.

TYPE: bool or None DEFAULT: None

lower_closed

Endpoint membership, closed by default; Boolean tensors may vary by batch row.

TYPE: bool or Tensor DEFAULT: True

upper_closed

Endpoint membership, closed by default; Boolean tensors may vary by batch row.

TYPE: bool or Tensor DEFAULT: True

Source code in src/quivers/continuous/measure.py
def __init__(
    self,
    base: Distribution,
    low: Tensor | float | None = None,
    high: Tensor | float | None = None,
    validate_args: bool | None = None,
    *,
    lower_closed: bool | Tensor = True,
    upper_closed: bool | Tensor = True,
) -> None:
    if low is None and high is None:
        raise ValueError(
            "Restrict: at least one of `low` or `high` must be "
            "supplied; an unrestricted base is just the base "
            "distribution itself."
        )
    self.lower_closed = _closed_flag(lower_closed, "lower_closed")
    self.upper_closed = _closed_flag(upper_closed, "upper_closed")
    self.base = base
    try:
        reference = _reference(base)
    except NotImplementedError:
        reference = torch.tensor(0.0)
    self.low = (
        torch.as_tensor(low, dtype=torch.float64, device=reference.device)
        if low is not None
        else None
    )
    self.high = (
        torch.as_tensor(high, dtype=torch.float64, device=reference.device)
        if high is not None
        else None
    )
    if not base.event_shape:
        shape = torch.broadcast_shapes(
            base.batch_shape,
            *(
                value.shape
                for value in (
                    self.low,
                    self.high,
                    self.lower_closed,
                    self.upper_closed,
                )
                if isinstance(value, Tensor)
            ),
        )
        if shape != base.batch_shape:
            self.base = base.expand(shape)
    super().__init__(
        batch_shape=self.base.batch_shape,
        event_shape=self.base.event_shape,
        validate_args=validate_args,
    )

support

support() -> Constraint

Intersect the base support with the exact interval event.

RETURNS DESCRIPTION
Constraint

Includes closed endpoint atoms and excludes open endpoints.

Source code in src/quivers/continuous/measure.py
@_constraints.dependent_property
def support(self) -> _constraints.Constraint:
    """Intersect the base support with the exact interval event.

    Returns
    -------
    Constraint
        Includes closed endpoint atoms and excludes open endpoints.
    """
    return _RestrictedSupport(self)

log_normalizer

log_normalizer() -> Tensor

Log of the raw total mass, one value per batch entry.

RETURNS DESCRIPTION
Tensor

Log of the raw total mass, one value per batch entry.

Source code in src/quivers/continuous/measure.py
def log_normalizer(self) -> Tensor:
    # All base families share endpoint-aware event masses. Internal
    # tail arithmetic remains wide; the public normalizer retains
    # the base's dtype and device.
    """Log of the raw total mass, one value per batch entry.

    Returns
    -------
    Tensor
        Log of the raw total mass, one value per batch entry."""
    try:
        return log_interval_mass(
            self.base,
            self.low,
            self.high,
            lower_closed=self.lower_closed,
            upper_closed=self.upper_closed,
        ).to(_reference(self.base))
    except NotImplementedError:
        symmetric = _symmetric_fold_log_normalizer(
            self.base,
            self.low,
            self.high,
        )
        if symmetric is not None:
            return symmetric
        raise

log_interval_mass

log_interval_mass(low, high, *, lower_closed=True, upper_closed=True)

Query the raw mass of an intersection without normalizing twice.

PARAMETER DESCRIPTION
low

Lower event bound; None leaves that side unbounded.

TYPE: object

high

Upper event bound; None leaves that side unbounded.

TYPE: object

lower_closed

Whether the lower endpoint belongs to the event.

TYPE: object DEFAULT: True

upper_closed

Whether the upper endpoint belongs to the event.

TYPE: object DEFAULT: True

RETURNS DESCRIPTION
object

Raw log mass on the requested interval, retaining independent batch axes.

Source code in src/quivers/continuous/measure.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Query the raw mass of an intersection without normalizing twice.

    Parameters
    ----------
    low : object
        Lower event bound; None leaves that side unbounded.
    high : object
        Upper event bound; None leaves that side unbounded.
    lower_closed : object
        Whether the lower endpoint belongs to the event.
    upper_closed : object
        Whether the upper endpoint belongs to the event.

    Returns
    -------
    object
        Raw log mass on the requested interval, retaining independent batch axes."""
    reference = _reference(self.base)
    low = (
        None
        if low is None
        else torch.as_tensor(low, dtype=torch.float64, device=reference.device)
    )
    high = (
        None
        if high is None
        else torch.as_tensor(high, dtype=torch.float64, device=reference.device)
    )
    low, lower_closed = _intersection_bound(
        self.low, low, self.lower_closed, lower_closed, lower=True
    )
    high, upper_closed = _intersection_bound(
        self.high, high, self.upper_closed, upper_closed, lower=False
    )
    return log_interval_mass(
        self.base, low, high, lower_closed=lower_closed, upper_closed=upper_closed
    )

expand

expand(batch_shape, _instance=None)

Broadcast the retained restriction without changing endpoint semantics.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch shape.

TYPE: object

_instance

Unused Torch expansion instance.

TYPE: object DEFAULT: None

RETURNS DESCRIPTION
object

Distribution with the requested batch shape and retained construction.

Source code in src/quivers/continuous/measure.py
def expand(self, batch_shape, _instance=None):
    """Broadcast the retained restriction without changing endpoint semantics.

    Parameters
    ----------
    batch_shape : object
        Requested broadcast batch shape.
    _instance : object
        Unused Torch expansion instance.

    Returns
    -------
    object
        Distribution with the requested batch shape and retained construction."""
    return Restrict(
        self.base.expand(batch_shape),
        self.low,
        self.high,
        lower_closed=self.lower_closed,
        upper_closed=self.upper_closed,
    )

atom_reference

atom_reference(value: Tensor) -> Tensor

Preserve the base carrier even when restriction removes its mass.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Membership in the fixed base atomic carrier.

Source code in src/quivers/continuous/measure.py
def atom_reference(self, value: Tensor) -> Tensor:
    """Preserve the base carrier even when restriction removes its mass.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Membership in the fixed base atomic carrier.
    """
    from quivers.continuous._atoms import atom_reference

    return atom_reference(self.base, value)

log_atom_mass

log_atom_mass(value: Tensor) -> Tensor

Restrict base singleton masses using the retained endpoint policy.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw singleton log mass inside the restriction.

Source code in src/quivers/continuous/measure.py
def log_atom_mass(self, value: Tensor) -> Tensor:
    """Restrict base singleton masses using the retained endpoint policy.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Raw singleton log mass inside the restriction.
    """
    from quivers.continuous._atoms import log_atom_mass

    return torch.where(
        self._inside(value), log_atom_mass(self.base, value), -torch.inf
    )

log_prob

log_prob(value: Tensor) -> Tensor

Raw log density or mass at the evaluation points.

PARAMETER DESCRIPTION
value

Evaluation points, broadcast against the distribution batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw log density or mass at the evaluation points.

Source code in src/quivers/continuous/measure.py
def log_prob(self, value: Tensor) -> Tensor:
    """Raw log density or mass at the evaluation points.

    Parameters
    ----------
    value : Tensor
        Evaluation points, broadcast against the distribution batch.

    Returns
    -------
    Tensor
        Raw log density or mass at the evaluation points."""
    from quivers.continuous._atoms import _point, safe_log_prob

    point = _point(self.base, value, reject_nan=False)
    inside = self._inside(point)
    if self.event_shape:
        inside = inside.all(
            tuple(range(inside.ndim - len(self.event_shape), inside.ndim))
        )
    return safe_log_prob(self.base, point, active=inside)

sample

sample(sample_shape: Size = Size()) -> Tensor

Draw from the restricted, renormalised measure.

A base with a closed-form CDF and inverse CDF is drawn by inversion: a uniform draw between the CDF at the two ends of the interval, mapped back through the inverse CDF, which is exactly the base conditioned on the interval. Any other base is drawn by rejection one entry at a time: each entry outside the interval is redrawn from the base until it falls inside, so every entry is an independent draw of the conditioned base.

PARAMETER DESCRIPTION
sample_shape

The leading sample shape.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws of shape sample_shape + batch_shape + event_shape, each inside the interval.

RAISES DESCRIPTION
ValueError

If the restricted measure has zero or nonfinite total mass.

RuntimeError

If rejection leaves an entry outside the interval after _REJECTION_ROUNDS redraws, which happens only when the interval holds a vanishing share of the base's mass.

Source code in src/quivers/continuous/measure.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draw from the restricted, renormalised measure.

    A base with a closed-form CDF and inverse CDF is drawn by
    inversion: a uniform draw between the CDF at the two ends of
    the interval, mapped back through the inverse CDF, which is
    exactly the base conditioned on the interval. Any other base is
    drawn by rejection one entry at a time: each entry outside the
    interval is redrawn from the base until it falls inside, so
    every entry is an independent draw of the conditioned base.

    Parameters
    ----------
    sample_shape : torch.Size
        The leading sample shape.

    Returns
    -------
    Tensor
        Draws of shape ``sample_shape + batch_shape + event_shape``,
        each inside the interval.

    Raises
    ------
    ValueError
        If the restricted measure has zero or nonfinite total mass.
    RuntimeError
        If rejection leaves an entry outside the interval after
        `_REJECTION_ROUNDS` redraws, which happens only when the
        interval holds a vanishing share of the base's mass.
    """
    return self._sample_active(
        sample_shape,
        torch.ones(
            self.batch_shape, dtype=torch.bool, device=_reference(self.base).device
        ),
    )

Pushforward

Pushforward(base: Distribution, bijector: Bijector, validate_args: bool | None = None)

Bases: Measure

Pushforward of a base distribution through a bijector.

Implements \(f_*\mu\), the measure whose log-density at y is base.log_prob(b.inverse(y)) + b.inverse_log_det_jacobian(y). Functorial in b: composing bijectors composes the pushforward.

Does not commute with Restrict in general; the compiler's rewrite pass handles the cases that do (monotone bijectors with interval restrictions).

PARAMETER DESCRIPTION
base

Underlying distribution or raw measure.

TYPE: Distribution

bijector

Invertible measurable coordinate transformation.

TYPE: Bijector

validate_args

Optional Torch argument-validation policy.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/measure.py
def __init__(
    self,
    base: Distribution,
    bijector: Bijector,
    validate_args: bool | None = None,
) -> None:
    self.base = base
    self.bijector = bijector
    super().__init__(
        batch_shape=base.batch_shape,
        event_shape=bijector.forward_shape(base.event_shape),
        validate_args=validate_args,
    )

support

support() -> Constraint

Constraint describing valid response values.

RETURNS DESCRIPTION
Constraint

Constraint describing valid response values.

Source code in src/quivers/continuous/measure.py
@_constraints.dependent_property
def support(self) -> _constraints.Constraint:
    """Constraint describing valid response values.

    Returns
    -------
    _constraints.Constraint
        Constraint describing valid response values."""
    return _constraints.real

log_normalizer

log_normalizer() -> Tensor

Preserve the base measure's raw mass under the bijection.

RETURNS DESCRIPTION
Tensor

Log total mass on the retained batch axes.

Source code in src/quivers/continuous/measure.py
def log_normalizer(self) -> Tensor:
    """Preserve the base measure's raw mass under the bijection.

    Returns
    -------
    Tensor
        Log total mass on the retained batch axes.
    """
    return _native_log_mass(self.base, batch_axes=len(self.base.batch_shape))

log_interval_mass

log_interval_mass(low, high, *, lower_closed=True, upper_closed=True)

Pull an interval back through the bijector's scalar capability.

PARAMETER DESCRIPTION
low

Lower event bound; None leaves that side unbounded.

TYPE: object

high

Upper event bound; None leaves that side unbounded.

TYPE: object

lower_closed

Whether the lower endpoint belongs to the event.

TYPE: object DEFAULT: True

upper_closed

Whether the upper endpoint belongs to the event.

TYPE: object DEFAULT: True

RETURNS DESCRIPTION
object

Raw log mass on the requested interval, retaining independent batch axes.

Source code in src/quivers/continuous/measure.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Pull an interval back through the bijector's scalar capability.

    Parameters
    ----------
    low : object
        Lower event bound; None leaves that side unbounded.
    high : object
        Upper event bound; None leaves that side unbounded.
    lower_closed : object
        Whether the lower endpoint belongs to the event.
    upper_closed : object
        Whether the upper endpoint belongs to the event.

    Returns
    -------
    object
        Raw log mass on the requested interval, retaining independent batch axes."""
    reference = _reference(self.base)
    low = torch.as_tensor(
        -torch.inf if low is None else low,
        dtype=torch.float64,
        device=reference.device,
    )
    high = torch.as_tensor(
        torch.inf if high is None else high,
        dtype=torch.float64,
        device=reference.device,
    )
    low, high = self.bijector._interval_preimage(low, high)
    return log_interval_mass(
        self.base, low, high, lower_closed=lower_closed, upper_closed=upper_closed
    )

atom_reference

atom_reference(value: Tensor) -> Tensor

Pull the atomic carrier back through the retained bijection.

PARAMETER DESCRIPTION
value

Query points in the image space.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Membership in the image of the base carrier.

Source code in src/quivers/continuous/measure.py
def atom_reference(self, value: Tensor) -> Tensor:
    """Pull the atomic carrier back through the retained bijection.

    Parameters
    ----------
    value : Tensor
        Query points in the image space.

    Returns
    -------
    Tensor
        Membership in the image of the base carrier.
    """
    from quivers.continuous._atoms import atom_reference

    return atom_reference(self.base, self.bijector.inverse(value))

log_atom_mass

log_atom_mass(value: Tensor) -> Tensor

Transport singleton masses without a density Jacobian.

PARAMETER DESCRIPTION
value

Query points in the image space.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw singleton log mass in the image space.

Source code in src/quivers/continuous/measure.py
def log_atom_mass(self, value: Tensor) -> Tensor:
    """Transport singleton masses without a density Jacobian.

    Parameters
    ----------
    value : Tensor
        Query points in the image space.

    Returns
    -------
    Tensor
        Raw singleton log mass in the image space.
    """
    from quivers.continuous._atoms import log_atom_mass

    return log_atom_mass(self.base, self.bijector.inverse(value))

log_prob

log_prob(value: Tensor) -> Tensor

Raw log density or mass at the evaluation points.

PARAMETER DESCRIPTION
value

Evaluation points, broadcast against the distribution batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw log density or mass at the evaluation points.

RAISES DESCRIPTION
NotImplementedError

If a mixed vector law requires an undeclared stratified reference.

Source code in src/quivers/continuous/measure.py
def log_prob(self, value: Tensor) -> Tensor:
    """Raw log density or mass at the evaluation points.

    Parameters
    ----------
    value : Tensor
        Evaluation points, broadcast against the distribution batch.

    Returns
    -------
    Tensor
        Raw log density or mass at the evaluation points.

    Raises
    ------
    NotImplementedError
        If a mixed vector law requires an undeclared stratified reference.
    """
    from quivers.continuous._atoms import (
        atom_reference,
        log_atom_mass,
        safe_log_prob,
    )

    x = self.bijector.inverse(value)
    if self.event_shape:
        if self._atomicity == "discrete":
            return self.base.log_prob(x)
        if self._atomicity == "mixed":
            raise NotImplementedError(
                "mixed vector transport requires a stratified reference measure"
            )
        determinant = self.bijector.inverse_log_det_jacobian(value)
        dims = len(self.base.event_shape) - self.bijector.jacobian_event_dim
        if dims:
            determinant = determinant.sum(tuple(range(-dims, 0)))
        return self.base.log_prob(x) + determinant
    atomic = atom_reference(self.base, x)
    base_lp = safe_log_prob(self.base, x, active=~atomic)
    log_det = self.bijector.inverse_log_det_jacobian(value)
    return torch.where(atomic, log_atom_mass(self.base, x), base_lp + log_det)

sample

sample(sample_shape: Size = Size()) -> Tensor

Draws from the normalized law with leading sample dimensions.

PARAMETER DESCRIPTION
sample_shape

Leading independent sampling dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws from the normalized law with leading sample dimensions.

Source code in src/quivers/continuous/measure.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draws from the normalized law with leading sample dimensions.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading independent sampling dimensions.

    Returns
    -------
    Tensor
        Draws from the normalized law with leading sample dimensions."""
    x = self.base.sample(sample_shape)
    return self.bijector.forward(x)

Mixture

Mixture(weights: Tensor, components: list[Distribution], validate_args: bool | None = None)

Bases: Measure

Finite mixture of arbitrary-family components.

weights is a vector summing to one (or, in the sub-measure regime, any non-negative vector; the total mass is the sum). components is a list of Distribution instances, possibly of different families and possibly including PointMass for inflation / hurdle structure.

The log-density is logsumexp(log_weights + log_components) over the component axis, broadcasting weights against the distribution batch shape. The symbolic log-normaliser is log(sum_k w_k * Z_k) where Z_k is the per-component normaliser (in particular when components are themselves sub-measures from Restrict).

Associativity (the Giry monad's multiplication law) is canonicalised by flatten(), which the compiler's rewrite pass calls before lowering.

PyMC issue #5533 documents how nested-mixture composition breaks in production PPLs; the operator algebra closes the gap.

PARAMETER DESCRIPTION
weights

Nonnegative raw component weights on the last axis.

TYPE: Tensor

components

Laws with the same event shape and broadcastable batches.

TYPE: list[Distribution]

validate_args

Optional Torch argument-validation policy.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/measure.py
def __init__(
    self,
    weights: Tensor,
    components: list[Distribution],
    validate_args: bool | None = None,
) -> None:
    if not components:
        raise ValueError("Mixture: components list must be non-empty")
    if not weights.ndim:
        raise ValueError(
            "Mixture weights must be finite nonnegative values with a component axis"
        )
    demand(
        torch.isfinite(weights) & (weights >= 0),
        lambda: ValueError(
            "Mixture weights must be finite nonnegative values with a component axis"
        ),
    )
    if any(
        component.event_shape != components[0].event_shape
        for component in components[1:]
    ):
        raise ValueError("Mixture components must have the same event shape")
    if weights.shape[-1] != len(components):
        raise ValueError(
            f"Mixture: weights last-dim {weights.shape[-1]} must "
            f"equal len(components) {len(components)}"
        )
    self.weights = weights
    self.components = list(components)
    self._num_components = len(components)
    batch_shape = weights.shape[:-1]
    for c in components:
        batch_shape = torch.broadcast_shapes(batch_shape, c.batch_shape)
    super().__init__(
        batch_shape=batch_shape,
        event_shape=components[0].event_shape,
        validate_args=validate_args,
    )

num_components property

num_components: int

Number of retained mixture components.

RETURNS DESCRIPTION
int

Number of retained mixture components.

component_probabilities property

component_probabilities: Tensor

Normalized probabilities of the components.

RETURNS DESCRIPTION
Tensor

w_k Z_k / sum_j w_j Z_j on the batch and component axes, where Z_k is the raw mass of component k.

mean property

mean: Tensor

Mean of the normalized mixture, sum_k p_k E_k[Y].

RETURNS DESCRIPTION
Tensor

The mean on the batch and event axes.

RAISES DESCRIPTION
NotImplementedError

If a component has no analytic mean.

variance property

variance: Tensor

Variance of the normalized mixture by the law of total variance.

RETURNS DESCRIPTION
Tensor

sum_k p_k (Var_k + E_k^2) - E^2 on the batch and event axes.

RAISES DESCRIPTION
NotImplementedError

If a component has no analytic mean or variance.

support

support() -> Constraint

Constraint describing valid response values.

RETURNS DESCRIPTION
Constraint

Constraint describing valid response values.

Source code in src/quivers/continuous/measure.py
@_constraints.dependent_property
def support(self) -> _constraints.Constraint:
    """Constraint describing valid response values.

    Returns
    -------
    _constraints.Constraint
        Constraint describing valid response values."""
    return _constraints.real

log_normalizer

log_normalizer() -> Tensor

Read raw total mass using the common weighted measure sum.

RETURNS DESCRIPTION
Tensor

Log mass on each mixture batch entry.

Source code in src/quivers/continuous/measure.py
def log_normalizer(self) -> Tensor:
    """Read raw total mass using the common weighted measure sum.

    Returns
    -------
    Tensor
        Log mass on each mixture batch entry.
    """
    return self._weighted_score(
        [
            _native_log_mass(component, batch_axes=len(component.batch_shape))
            for component in self.components
        ]
    )

log_interval_mass

log_interval_mass(low, high, *, lower_closed=True, upper_closed=True)

Add raw component event masses, including any point atoms.

PARAMETER DESCRIPTION
low

Lower event bound; None leaves that side unbounded.

TYPE: object

high

Upper event bound; None leaves that side unbounded.

TYPE: object

lower_closed

Whether the lower endpoint belongs to the event.

TYPE: object DEFAULT: True

upper_closed

Whether the upper endpoint belongs to the event.

TYPE: object DEFAULT: True

RETURNS DESCRIPTION
object

Raw log mass on the requested interval, retaining independent batch axes.

Source code in src/quivers/continuous/measure.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Add raw component event masses, including any point atoms.

    Parameters
    ----------
    low : object
        Lower event bound; None leaves that side unbounded.
    high : object
        Upper event bound; None leaves that side unbounded.
    lower_closed : object
        Whether the lower endpoint belongs to the event.
    upper_closed : object
        Whether the upper endpoint belongs to the event.

    Returns
    -------
    object
        Raw log mass on the requested interval, retaining independent batch axes."""
    return self._weighted_score(
        [
            log_interval_mass(
                component,
                low,
                high,
                lower_closed=lower_closed,
                upper_closed=upper_closed,
            )
            for component in self.components
        ]
    )

expand

expand(batch_shape, _instance=None)

Broadcast the common mixture batch and its component weights.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch shape.

TYPE: object

_instance

Unused Torch expansion instance.

TYPE: object DEFAULT: None

RETURNS DESCRIPTION
object

Distribution with the requested batch shape and retained construction.

Source code in src/quivers/continuous/measure.py
def expand(self, batch_shape, _instance=None):
    """Broadcast the common mixture batch and its component weights.

    Parameters
    ----------
    batch_shape : object
        Requested broadcast batch shape.
    _instance : object
        Unused Torch expansion instance.

    Returns
    -------
    object
        Distribution with the requested batch shape and retained construction."""
    return Mixture(
        self.weights.expand(*batch_shape, self._num_components),
        [component.expand(batch_shape) for component in self.components],
    )

atom_reference

atom_reference(value: Tensor) -> Tensor

Take the union of component carriers, including zero-weight components.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Membership in at least one component atomic carrier.

Source code in src/quivers/continuous/measure.py
def atom_reference(self, value: Tensor) -> Tensor:
    """Take the union of component carriers, including zero-weight components.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Membership in at least one component atomic carrier.
    """
    from quivers.continuous._atoms import atom_reference

    carriers = torch.broadcast_tensors(
        *(atom_reference(c, value) for c in self.components)
    )
    return torch.stack(carriers, -1).any(-1)

log_atom_mass

log_atom_mass(value: Tensor) -> Tensor

Add weighted singleton masses under the common atomic carrier.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Weighted raw singleton log mass.

Source code in src/quivers/continuous/measure.py
def log_atom_mass(self, value: Tensor) -> Tensor:
    """Add weighted singleton masses under the common atomic carrier.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Weighted raw singleton log mass.
    """
    from quivers.continuous._atoms import log_atom_mass

    return self._weighted_score([log_atom_mass(c, value) for c in self.components])

log_prob

log_prob(value: Tensor) -> Tensor

Raw log density or mass at the evaluation points.

PARAMETER DESCRIPTION
value

Evaluation points, broadcast against the distribution batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw log density or mass at the evaluation points.

RAISES DESCRIPTION
NotImplementedError

If mixed vector components lack a common stratified reference measure.

Source code in src/quivers/continuous/measure.py
def log_prob(self, value: Tensor) -> Tensor:
    """Raw log density or mass at the evaluation points.

    Parameters
    ----------
    value : Tensor
        Evaluation points, broadcast against the distribution batch.

    Returns
    -------
    Tensor
        Raw log density or mass at the evaluation points.

    Raises
    ------
    NotImplementedError
        If mixed vector components lack a common stratified reference measure.
    """
    from quivers.continuous._atoms import safe_log_prob

    value = torch.as_tensor(value, device=self.weights.device)
    atomic = atom_score = None
    if self.event_shape:
        if self._atomicity == "mixed":
            raise NotImplementedError(
                "mixed vector mixtures require a common stratified reference measure"
            )
        scores = [component.log_prob(value) for component in self.components]
    else:
        atomic = self.atom_reference(value)
        atom_score = self.log_atom_mass(value)
        scores = [
            safe_log_prob(component, value, active=~atomic)
            for component in self.components
        ]
    density = self._weighted_score(scores)
    if atomic is None:
        return density
    assert atom_score is not None
    return torch.where(atomic, atom_score, density)

sample

sample(sample_shape: Size = Size()) -> Tensor

Draws from the normalized law with leading sample dimensions.

PARAMETER DESCRIPTION
sample_shape

Leading independent sampling dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws from the normalized law with leading sample dimensions.

Source code in src/quivers/continuous/measure.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draws from the normalized law with leading sample dimensions.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading independent sampling dimensions.

    Returns
    -------
    Tensor
        Draws from the normalized law with leading sample dimensions."""
    active = torch.ones(
        self.batch_shape, dtype=torch.bool, device=self.weights.device
    )
    return self._sample_active(sample_shape, active)

flatten

flatten() -> Mixture

Apply the Giry-monad-multiplication associativity rule: any nested Mixture component is replaced by its components with weights scaled by the outer weight. Returns a flat Mixture whose components are not themselves Mixture instances.

RETURNS DESCRIPTION
Mixture

Equivalent mixture with nested component weights multiplied.

Source code in src/quivers/continuous/measure.py
def flatten(self) -> Mixture:
    """Apply the Giry-monad-multiplication associativity rule:
    any nested `Mixture` component is replaced by its components
    with weights scaled by the outer weight. Returns a flat
    `Mixture` whose components are not themselves `Mixture`
    instances.

    Returns
    -------
    Mixture
        Equivalent mixture with nested component weights multiplied."""
    flat_weights_parts = []
    flat_components: list[Distribution] = []
    for k, comp in enumerate(self.components):
        w_k = self.weights[..., k : k + 1]
        if isinstance(comp, Mixture):
            inner = comp.flatten()
            flat_weights_parts.append(w_k * inner.weights)
            flat_components.extend(inner.components)
        else:
            flat_weights_parts.append(w_k)
            flat_components.append(comp)
    flat_weights = torch.cat(flat_weights_parts, dim=-1)
    return Mixture(flat_weights, flat_components)

pushforward_inside

pushforward_inside(bijector) -> Mixture

Push a single bijector inside every component:

\[g_*\left(\sum_k \pi_k\,\mu_k\right) = \sum_k \pi_k\,g_*\mu_k.\]

Functoriality of the Giry monad on measurable isomorphisms; the per-component pushforward is the canonical shape the renderer prefers.

PARAMETER DESCRIPTION
bijector

Measurable invertible coordinate transformation.

TYPE: object

RETURNS DESCRIPTION
Mixture

Mixture obtained by applying the bijector to each component.

Source code in src/quivers/continuous/measure.py
def pushforward_inside(self, bijector) -> Mixture:
    """Push a single bijector inside every component:

    $$g_*\\left(\\sum_k \\pi_k\\,\\mu_k\\right)
      = \\sum_k \\pi_k\\,g_*\\mu_k.$$

    Functoriality of the Giry monad on measurable isomorphisms;
    the per-component pushforward is the canonical shape the
    renderer prefers.

    Parameters
    ----------
    bijector : object
        Measurable invertible coordinate transformation.

    Returns
    -------
    Mixture
        Mixture obtained by applying the bijector to each component."""
    new_components = [Pushforward(c, bijector) for c in self.components]
    return Mixture(self.weights, new_components)

restrict_to

restrict_to(low=None, high=None, *, lower_closed=True, upper_closed=True) -> Mixture

Condition the raw mixture on an endpoint-aware interval.

Components retain their restricted raw measures. Dividing each original weight by the common event mass normalizes their sum; component selection then uses the same weighted masses as every other mixture. Zero-mass components need no separate normalization.

PARAMETER DESCRIPTION
low

Optional event bounds.

TYPE: Tensor or float or None DEFAULT: None

high

Optional event bounds.

TYPE: Tensor or float or None DEFAULT: None

lower_closed

Endpoint membership, closed by default.

TYPE: bool or Tensor DEFAULT: True

upper_closed

Endpoint membership, closed by default.

TYPE: bool or Tensor DEFAULT: True

RETURNS DESCRIPTION
Mixture

A probability measure on the requested event. Its retained component weights multiply raw restricted measures.

RAISES DESCRIPTION
ValueError

If the event has zero or nonfinite mass on any batch entry.

Source code in src/quivers/continuous/measure.py
def restrict_to(
    self, low=None, high=None, *, lower_closed=True, upper_closed=True
) -> Mixture:
    """Condition the raw mixture on an endpoint-aware interval.

    Components retain their restricted raw measures. Dividing each
    original weight by the common event mass normalizes their sum;
    component selection then uses the same weighted masses as every
    other mixture. Zero-mass components need no separate normalization.

    Parameters
    ----------
    low, high : Tensor or float or None
        Optional event bounds.
    lower_closed, upper_closed : bool or Tensor
        Endpoint membership, closed by default.

    Returns
    -------
    Mixture
        A probability measure on the requested event. Its retained
        component weights multiply raw restricted measures.

    Raises
    ------
    ValueError
        If the event has zero or nonfinite mass on any batch entry.
    """
    components = [
        Restrict(
            component,
            low,
            high,
            lower_closed=lower_closed,
            upper_closed=upper_closed,
        )
        for component in self.components
    ]
    raw = Mixture(self.weights, components)
    mass = raw.log_normalizer()
    demand(
        torch.isfinite(mass),
        lambda: ValueError(
            "Mixture restriction requires finite positive event mass"
        ),
    )
    return Mixture(torch.exp(self._log_weights() - mass.unsqueeze(-1)), components)

lift_point_masses

lift_point_masses() -> Mixture

Surface the PointMass components as a Bernoulli-style branch with the non-degenerate components in the complementary mixture. Returns a Mixture whose components are pairwise measure-disjoint: each PointMass(x) carries only its spike, and the non-degenerate components live in the complement.

For a single PointMass plus a single non-degenerate component (the ZIP / hurdle canonical shape), the rewrite is a no-op: the current form is already the Bernoulli-branch factorisation the renderers expect. For Mixtures with multiple PointMass components at distinct values, returns a canonical form with the point masses ordered first.

RETURNS DESCRIPTION
Mixture

Equivalent mixture with atomic components placed first.

Source code in src/quivers/continuous/measure.py
def lift_point_masses(self) -> Mixture:
    """Surface the `PointMass` components as a Bernoulli-style
    branch with the non-degenerate components in the
    complementary mixture. Returns a `Mixture` whose components
    are pairwise measure-disjoint: each `PointMass(x)` carries
    only its spike, and the non-degenerate components live in the
    complement.

    For a single `PointMass` plus a single non-degenerate
    component (the ZIP / hurdle canonical shape), the rewrite is
    a no-op: the current form is already the Bernoulli-branch
    factorisation the renderers expect. For Mixtures with
    multiple `PointMass` components at distinct values, returns a
    canonical form with the point masses ordered first.

    Returns
    -------
    Mixture
        Equivalent mixture with atomic components placed first."""
    point_masses = []
    rest = []
    point_mass_weights = []
    rest_weights = []
    for k, comp in enumerate(self.components):
        w_k = self.weights[..., k : k + 1]
        if isinstance(comp, PointMass):
            point_masses.append(comp)
            point_mass_weights.append(w_k)
        else:
            rest.append(comp)
            rest_weights.append(w_k)
    if not point_masses:
        return self
    new_components = point_masses + rest
    new_weights = torch.cat(point_mass_weights + rest_weights, dim=-1)
    return Mixture(new_weights, new_components)

Independent

Independent(base: Distribution, reinterpreted_batch_ndims: int | Tensor, validate_args: bool | None = None)

Bases: Measure

Reinterpret the last reinterpreted_batch_ndims batch dims of base as event dims. Wraps PyTorch's Independent.

The log-density sums base.log_prob(value) over the reinterpreted dims; the log-normaliser sums in the same direction when base is itself a sub-measure.

PARAMETER DESCRIPTION
base

Independent coordinate laws or raw measures.

TYPE: Distribution

reinterpreted_batch_ndims

Nonnegative number of trailing batch axes forming one event. Zero preserves the base law's batch and event axes. A tensor must be scalar and carry an integer value.

TYPE: int or Tensor

validate_args

Optional Torch argument-validation policy.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/measure.py
def __init__(
    self,
    base: Distribution,
    reinterpreted_batch_ndims: int | Tensor,
    validate_args: bool | None = None,
) -> None:
    count_value: object = reinterpreted_batch_ndims
    if isinstance(count_value, Tensor):
        if count_value.ndim != 0:
            raise TypeError(
                "Independent: reinterpreted_batch_ndims must be a scalar integer"
            )
        count_value = count_value.item()
    count = independent_ndims(count_value, len(base.batch_shape))
    self.base = base
    self.reinterpreted_batch_ndims = count
    self._inner = torch.distributions.Independent(
        base,
        count,
    )
    super().__init__(
        batch_shape=self._inner.batch_shape,
        event_shape=self._inner.event_shape,
        validate_args=validate_args,
    )

has_rsample property

has_rsample: bool

Whether the base law supports a pathwise sample.

RETURNS DESCRIPTION
bool

The base law's declared sampling capability.

mean property

mean: Tensor

Base means with the declared batch and event axes retained.

RETURNS DESCRIPTION
Tensor

Coordinate means, when defined by the base law.

variance property

variance: Tensor

Base marginal variances with every coordinate axis retained.

RETURNS DESCRIPTION
Tensor

Marginal coordinate variances, when defined by the base law.

rsample

rsample(sample_shape: Size | tuple[int, ...] | list[int] = Size()) -> Tensor

Draw pathwise samples only when the base law supports them.

PARAMETER DESCRIPTION
sample_shape

Additional leading independent sample axes.

TYPE: torch.Size or tuple of int or list of int DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Base pathwise draws with the same coordinate layout.

RAISES DESCRIPTION
NotImplementedError

If the base law has no pathwise sampler.

Source code in src/quivers/continuous/measure.py
def rsample(
    self, sample_shape: torch.Size | tuple[int, ...] | list[int] = torch.Size()
) -> Tensor:
    """Draw pathwise samples only when the base law supports them.

    Parameters
    ----------
    sample_shape : torch.Size or tuple of int or list of int
        Additional leading independent sample axes.

    Returns
    -------
    Tensor
        Base pathwise draws with the same coordinate layout.

    Raises
    ------
    NotImplementedError
        If the base law has no pathwise sampler.
    """
    if not self.has_rsample:
        raise NotImplementedError("Independent base law has no pathwise sampler")
    return self._inner.rsample(sample_shape)

support

support() -> Constraint

Constraint describing valid response values.

RETURNS DESCRIPTION
Constraint

Constraint describing valid response values.

Source code in src/quivers/continuous/measure.py
@_constraints.dependent_property
def support(self) -> _constraints.Constraint:
    """Constraint describing valid response values.

    Returns
    -------
    _constraints.Constraint
        Constraint describing valid response values."""
    return self._inner.support

log_normalizer

log_normalizer() -> Tensor

Reduce raw mass over the newly declared independent event axes.

RETURNS DESCRIPTION
Tensor

Log total mass with only independent batch axes retained.

Source code in src/quivers/continuous/measure.py
def log_normalizer(self) -> Tensor:
    """Reduce raw mass over the newly declared independent event axes.

    Returns
    -------
    Tensor
        Log total mass with only independent batch axes retained.
    """
    inner = _native_log_mass(self.base, batch_axes=len(self.base.batch_shape))
    if self.reinterpreted_batch_ndims == 0:
        return inner
    return inner.sum(
        tuple(range(inner.ndim - self.reinterpreted_batch_ndims, inner.ndim))
    )

log_interval_mass

log_interval_mass(low, high, *, lower_closed=True, upper_closed=True)

Multiply independent coordinate event masses by adding their logarithms.

PARAMETER DESCRIPTION
low

Lower event bound; None leaves that side unbounded.

TYPE: object

high

Upper event bound; None leaves that side unbounded.

TYPE: object

lower_closed

Whether the lower endpoint belongs to the event.

TYPE: object DEFAULT: True

upper_closed

Whether the upper endpoint belongs to the event.

TYPE: object DEFAULT: True

RETURNS DESCRIPTION
object

Raw log mass on the requested interval, retaining independent batch axes.

Source code in src/quivers/continuous/measure.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Multiply independent coordinate event masses by adding their logarithms.

    Parameters
    ----------
    low : object
        Lower event bound; None leaves that side unbounded.
    high : object
        Upper event bound; None leaves that side unbounded.
    lower_closed : object
        Whether the lower endpoint belongs to the event.
    upper_closed : object
        Whether the upper endpoint belongs to the event.

    Returns
    -------
    object
        Raw log mass on the requested interval, retaining independent batch axes."""
    mass = log_interval_mass(
        self.base, low, high, lower_closed=lower_closed, upper_closed=upper_closed
    )
    if self.reinterpreted_batch_ndims == 0:
        return mass
    return mass.sum(
        tuple(range(mass.ndim - self.reinterpreted_batch_ndims, mass.ndim))
    )

atom_reference

atom_reference(value: Tensor) -> Tensor

Identify singleton atoms jointly across reinterpreted event axes.

PARAMETER DESCRIPTION
value

Queries with intrinsic event axes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether every coordinate belongs to its base atomic carrier.

Source code in src/quivers/continuous/measure.py
def atom_reference(self, value: Tensor) -> Tensor:
    """Identify singleton atoms jointly across reinterpreted event axes.

    Parameters
    ----------
    value : Tensor
        Queries with intrinsic event axes.

    Returns
    -------
    Tensor
        Whether every coordinate belongs to its base atomic carrier.
    """
    from quivers.continuous._atoms import atom_reference

    carrier = atom_reference(self.base, value)
    dims = self.reinterpreted_batch_ndims
    return carrier.all(tuple(range(-dims, 0))) if dims else carrier

log_atom_mass

log_atom_mass(value: Tensor) -> Tensor

Multiply coordinate singleton masses across declared event axes.

PARAMETER DESCRIPTION
value

Queries with intrinsic event axes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Joint singleton log mass.

Source code in src/quivers/continuous/measure.py
def log_atom_mass(self, value: Tensor) -> Tensor:
    """Multiply coordinate singleton masses across declared event axes.

    Parameters
    ----------
    value : Tensor
        Queries with intrinsic event axes.

    Returns
    -------
    Tensor
        Joint singleton log mass.
    """
    from quivers.continuous._atoms import log_atom_mass

    score = log_atom_mass(self.base, value)
    dims = self.reinterpreted_batch_ndims
    return score.sum(tuple(range(-dims, 0))) if dims else score

log_prob

log_prob(value: Tensor) -> Tensor

Raw log density or mass at the evaluation points.

PARAMETER DESCRIPTION
value

Evaluation points, broadcast against the distribution batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw log density or mass at the evaluation points.

Source code in src/quivers/continuous/measure.py
def log_prob(self, value: Tensor) -> Tensor:
    """Raw log density or mass at the evaluation points.

    Parameters
    ----------
    value : Tensor
        Evaluation points, broadcast against the distribution batch.

    Returns
    -------
    Tensor
        Raw log density or mass at the evaluation points."""
    score = self.base.log_prob(value)
    dims = self.reinterpreted_batch_ndims
    return score.sum(tuple(range(-dims, 0))) if dims else score

sample

sample(sample_shape: Size = Size()) -> Tensor

Draws from the normalized law with leading sample dimensions.

PARAMETER DESCRIPTION
sample_shape

Leading independent sampling dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws from the normalized law with leading sample dimensions.

Source code in src/quivers/continuous/measure.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draws from the normalized law with leading sample dimensions.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading independent sampling dimensions.

    Returns
    -------
    Tensor
        Draws from the normalized law with leading sample dimensions."""
    return self._inner.sample(sample_shape)

Normalize

Normalize(base: Distribution, validate_args: bool | None = None)

Bases: Measure

Rescale a sub-measure to a probability measure.

log_prob_normalized(value) = log_prob(value) - log_normalizer() by construction; this wrapper makes the normalisation explicit so downstream code can rely on log_normalizer() == 0. Use at the observe / sample boundary or whenever a probability measure is required (e.g. before sampling).

PARAMETER DESCRIPTION
base

Raw measure with finite positive total mass on every batch entry.

TYPE: Distribution

validate_args

Optional Torch argument-validation policy.

TYPE: bool or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If any base batch entry has zero or nonfinite total mass.

Source code in src/quivers/continuous/measure.py
def __init__(
    self,
    base: Distribution,
    validate_args: bool | None = None,
) -> None:
    self.base = base
    self._base_log_normalizer = _native_log_mass(
        base, batch_axes=len(base.batch_shape)
    )
    demand(
        torch.isfinite(self._base_log_normalizer),
        lambda: ValueError("Normalize requires a finite positive measure mass"),
    )
    super().__init__(
        batch_shape=base.batch_shape,
        event_shape=base.event_shape,
        validate_args=validate_args,
    )

mean property

mean: Tensor

Mean of a scalar law conditioned on an interval, without sampling.

RETURNS DESCRIPTION
Tensor

The truncated mean from a closed form, a finite sum, or deterministic quadrature, in the dtype of the base law.

RAISES DESCRIPTION
NotImplementedError

If the base is not the restriction of a scalar law to an interval, or no deterministic rule covers that law there.

support

support() -> Constraint

Constraint describing valid response values.

RETURNS DESCRIPTION
Constraint

Constraint describing valid response values.

Source code in src/quivers/continuous/measure.py
@_constraints.dependent_property
def support(self) -> _constraints.Constraint:
    """Constraint describing valid response values.

    Returns
    -------
    _constraints.Constraint
        Constraint describing valid response values."""
    return self.base.support

log_normalizer

log_normalizer() -> Tensor

Log of the raw total mass, one value per batch entry.

RETURNS DESCRIPTION
Tensor

Log of the raw total mass, one value per batch entry.

Source code in src/quivers/continuous/measure.py
def log_normalizer(self) -> Tensor:
    """Log of the raw total mass, one value per batch entry.

    Returns
    -------
    Tensor
        Log of the raw total mass, one value per batch entry."""
    return torch.zeros_like(self._base_log_normalizer)

log_interval_mass

log_interval_mass(low, high, *, lower_closed=True, upper_closed=True)

Normalize the same base event mass by the retained total mass.

PARAMETER DESCRIPTION
low

Lower event bound; None leaves that side unbounded.

TYPE: object

high

Upper event bound; None leaves that side unbounded.

TYPE: object

lower_closed

Whether the lower endpoint belongs to the event.

TYPE: object DEFAULT: True

upper_closed

Whether the upper endpoint belongs to the event.

TYPE: object DEFAULT: True

RETURNS DESCRIPTION
object

Raw log mass on the requested interval, retaining independent batch axes.

Source code in src/quivers/continuous/measure.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Normalize the same base event mass by the retained total mass.

    Parameters
    ----------
    low : object
        Lower event bound; None leaves that side unbounded.
    high : object
        Upper event bound; None leaves that side unbounded.
    lower_closed : object
        Whether the lower endpoint belongs to the event.
    upper_closed : object
        Whether the upper endpoint belongs to the event.

    Returns
    -------
    object
        Raw log mass on the requested interval, retaining independent batch axes."""
    return (
        log_interval_mass(
            self.base,
            low,
            high,
            lower_closed=lower_closed,
            upper_closed=upper_closed,
        )
        - self._base_log_normalizer
    )

expand

expand(batch_shape, _instance=None)

Broadcast a normalized measure through its underlying construction.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch shape.

TYPE: object

_instance

Unused Torch expansion instance.

TYPE: object DEFAULT: None

RETURNS DESCRIPTION
object

Distribution with the requested batch shape and retained construction.

Source code in src/quivers/continuous/measure.py
def expand(self, batch_shape, _instance=None):
    """Broadcast a normalized measure through its underlying construction.

    Parameters
    ----------
    batch_shape : object
        Requested broadcast batch shape.
    _instance : object
        Unused Torch expansion instance.

    Returns
    -------
    object
        Distribution with the requested batch shape and retained construction."""
    return Normalize(self.base.expand(batch_shape))

atom_reference

atom_reference(value: Tensor) -> Tensor

Preserve the base atomic carrier under normalization.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Membership in the base carrier.

Source code in src/quivers/continuous/measure.py
def atom_reference(self, value: Tensor) -> Tensor:
    """Preserve the base atomic carrier under normalization.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Membership in the base carrier.
    """
    from quivers.continuous._atoms import atom_reference

    return atom_reference(self.base, value)

log_atom_mass

log_atom_mass(value: Tensor) -> Tensor

Normalize raw base singleton masses exactly once.

PARAMETER DESCRIPTION
value

Query points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Normalized singleton log mass.

Source code in src/quivers/continuous/measure.py
def log_atom_mass(self, value: Tensor) -> Tensor:
    """Normalize raw base singleton masses exactly once.

    Parameters
    ----------
    value : Tensor
        Query points.

    Returns
    -------
    Tensor
        Normalized singleton log mass.
    """
    from quivers.continuous._atoms import log_atom_mass

    return log_atom_mass(self.base, value) - self._base_log_normalizer

log_prob

log_prob(value: Tensor) -> Tensor

Raw log density or mass at the evaluation points.

PARAMETER DESCRIPTION
value

Evaluation points, broadcast against the distribution batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw log density or mass at the evaluation points.

Source code in src/quivers/continuous/measure.py
def log_prob(self, value: Tensor) -> Tensor:
    """Raw log density or mass at the evaluation points.

    Parameters
    ----------
    value : Tensor
        Evaluation points, broadcast against the distribution batch.

    Returns
    -------
    Tensor
        Raw log density or mass at the evaluation points."""
    return self.base.log_prob(value) - self._base_log_normalizer

sample

sample(sample_shape: Size = Size()) -> Tensor

Draws from the normalized law with leading sample dimensions.

PARAMETER DESCRIPTION
sample_shape

Leading independent sampling dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws from the normalized law with leading sample dimensions.

Source code in src/quivers/continuous/measure.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draws from the normalized law with leading sample dimensions.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading independent sampling dimensions.

    Returns
    -------
    Tensor
        Draws from the normalized law with leading sample dimensions."""
    return self.base.sample(sample_shape)

truncated_law

truncated_law(base: Distribution, event: Mapping[str, Tensor | float | int | None] | None) -> Distribution

The sampling law of a response under its recording roles.

PARAMETER DESCRIPTION
base

The response law.

TYPE: Distribution

event

The bound recording roles. Only a truncation interval changes how a response is sampled; censoring says how it is recorded.

TYPE: Mapping[str, Tensor | float | int | None] or None

RETURNS DESCRIPTION
Distribution

base, normalized on its truncation interval when it has one.

Source code in src/quivers/continuous/measure.py
def truncated_law(
    base: Distribution, event: Mapping[str, Tensor | float | int | None] | None
) -> Distribution:
    """The sampling law of a response under its recording roles.

    Parameters
    ----------
    base : Distribution
        The response law.
    event : Mapping[str, Tensor | float | int | None] or None
        The bound recording roles. Only a truncation interval changes how
        a response is sampled; censoring says how it is recorded.

    Returns
    -------
    Distribution
        ``base``, normalized on its truncation interval when it has one.
    """
    roles: Mapping[str, Tensor | float | int | None] = {} if event is None else event
    lower, upper = roles.get("trunc_lower"), roles.get("trunc_upper")
    if lower is None and upper is None:
        return base
    truncated = getattr(base, "componentwise_truncation", None)
    if callable(truncated):
        law = truncated(lower, upper)
        assert isinstance(law, Distribution)
        return law
    return Normalize(Restrict(base, lower, upper))

normalize_at_boundary

normalize_at_boundary(d: Distribution) -> Distribution

Lift d to a probability measure if it is a sub-measure with non-zero log-normaliser; otherwise return d unchanged.

Called by the inline / observe path to enforce the "renormalise at the observe / sample boundary" invariant the sub-Giry algebra relies on.

PARAMETER DESCRIPTION
d

Native distribution or measure to normalize at an execution boundary.

TYPE: Distribution

RETURNS DESCRIPTION
Distribution

Probability law, with explicit normalization when required.

Source code in src/quivers/continuous/measure.py
def normalize_at_boundary(d: Distribution) -> Distribution:
    """Lift `d` to a probability measure if it is a sub-measure
    with non-zero log-normaliser; otherwise return `d` unchanged.

    Called by the inline / observe path to enforce the
    "renormalise at the observe / sample boundary" invariant the
    sub-Giry algebra relies on.

    Parameters
    ----------
    d : Distribution
        Native distribution or measure to normalize at an execution boundary.

    Returns
    -------
    Distribution
        Probability law, with explicit normalization when required."""
    if isinstance(d, Measure):
        norm = d.log_normalizer()
        if isinstance(norm, Tensor):
            if anywhere(norm.abs() > 1e-10):
                return Normalize(d)
        else:
            if abs(float(norm)) > 1e-10:
                return Normalize(d)
    return d

Cited sources

José M. Bernardo and Adrian F. M. Smith. Bayesian Theory. Wiley, 1994. URL: https://onlinelibrary.wiley.com/doi/book/10.1002/9780470316870, doi:10.1002/9780470316870.