Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Operations

This page documents the operations, such as sample, mean, and condition_on, and the errors a call raises when no route of an operation applies or the result is undefined. A call of an operation selects one of its routes, which are its implementations, and ranks exact routes before approximate ones. The convert operation is on Conversion, the inference methods that condition_on selects are on Inference methods, and the registry of the operations and their routes is on Registries for extensions.

For a kernel, given= first tries the operation's native exact conditional capabilities, then exact conditioning followed by an exact operation. The latter requires exact input binding and any necessary normalization. If either needs an approximation, the operation can select its Monte Carlo route using the requested num_samples, or, for expectation, the requested max_evaluations. Delegation to a bound law records the fidelity of binding, normalization, and the operation together. An explicit method selects the downstream operation's route; method_options also passes to binding and normalization.

Sampling

sample(d, sample_shape=())

Draw from a distribution.

Parameters:

Name Type Description Default
d Distribution

The law to draw from.

required
sample_shape int or sequence of int

The batch axes to prepend; () draws once, and a single int is one axis, so sample_shape=100 is sample_shape=(100,).

()

Returns:

Type Description
TrackedTerm

One draw at the kind the event spec names, such as a NumericArray or a Record; or, for a non-empty sample_shape, the batch form of that kind with the leading axes on a level named sample. A draw keeps d's outputs and is labeled by them, ~, and d's label, as mu ~ prior or (y, mu) ~ model, followed by ; and the paths d holds fixed, as mu ~ model; y. A batch of draws takes the label of one draw, so its element is labeled (mu ~ prior)[sample=0]. Under using(raw=True) the draws are returned as d._sample gives them, so a record-valued law's batch of draws is the nested mapping of its raw columns. A batch-valued event keeps its own levels for one draw, and a non-empty sample_shape adds the sample level before them.

Raises:

Type Description
ApplicabilityError

If sample_shape is malformed, the event spec has free dimensions, or a non-empty sample_shape meets a batch-valued event that already has a level named sample.

ResolutionError

If d does not sample.

Source code in probpipe/operations/_sample.py
@operation(result=_sample_result)
def sample(d: Distribution, sample_shape: SizesLike = ()):
    """Draw from a distribution.

    Parameters
    ----------
    d : Distribution
        The law to draw from.
    sample_shape : int or sequence of int
        The batch axes to prepend; ``()`` draws once, and a single int is one
        axis, so ``sample_shape=100`` is ``sample_shape=(100,)``.

    Returns
    -------
    TrackedTerm
        One draw at the kind the event spec names, such as a
        ``NumericArray`` or a ``Record``; or, for a non-empty *sample_shape*, the
        batch form of that kind with the leading axes on a level named
        ``sample``. A draw keeps *d*'s outputs and is labeled by them, ``~``,
        and *d*'s label, as ``mu ~ prior`` or ``(y, mu) ~ model``, followed by
        ``;`` and the paths *d* holds fixed, as ``mu ~ model; y``. A batch of
        draws takes the label of one draw, so its element is labeled
        ``(mu ~ prior)[sample=0]``. Under ``using(raw=True)`` the draws
        are returned as ``d._sample`` gives them, so a record-valued law's
        batch of draws is the nested mapping of its raw columns. A batch-valued
        event keeps its own levels for one draw, and a non-empty *sample_shape*
        adds the ``sample`` level before them.

    Raises
    ------
    ApplicabilityError
        If *sample_shape* is malformed, the event spec has free dimensions, or
        a non-empty *sample_shape* meets a batch-valued event that already has
        a level named ``sample``.
    ResolutionError
        If *d* does not sample.
    """

Densities

log_prob(d, value)

The normalized log-density of value under d.

Parameters:

Name Type Description Default
d Distribution

A law claiming SupportsLogProb.

required
value Any

One value conforming to d.event_spec.term_spec, or a batch of them; a scored value binds the law's symbolic dimensions for this call only. A law over such values lifts the call, which then returns the law of the log-density at its draws.

required

Returns:

Type Description
NumericArray or NumericArrayBatch

The log-density, or one per element of a batch value, at its levels, labeled log and d's notation, as log prior(mu), under the output log_prob.

Raises:

Type Description
ApplicabilityError

If value does not conform to the event spec.

ResolutionError

If d does not claim SupportsLogProb.

Source code in probpipe/operations/_density.py
@operation(result=_log_prob_result)
def log_prob(d: Distribution, value):
    """The normalized log-density of *value* under *d*.

    Parameters
    ----------
    d : Distribution
        A law claiming ``SupportsLogProb``.
    value : Any
        One value conforming to ``d.event_spec.term_spec``, or a batch of them; a
        scored value binds the law's symbolic dimensions for this call only. A
        law over such values lifts the call, which then returns the law of the
        log-density at its draws.

    Returns
    -------
    NumericArray or NumericArrayBatch
        The log-density, or one per element of a batch value, at its levels,
        labeled ``log`` and *d*'s notation, as ``log prior(mu)``, under the
        output ``log_prob``.

    Raises
    ------
    ApplicabilityError
        If *value* does not conform to the event spec.
    ResolutionError
        If *d* does not claim ``SupportsLogProb``.
    """

unnormalized_log_prob(d, value)

The log-density of value under d up to an additive constant.

Parameters:

Name Type Description Default
d Distribution

A law claiming SupportsUnnormalizedLogProb.

required
value Any

One value conforming to d.event_spec.term_spec, or a batch of them. A law over such values lifts the call, which then returns the law of the log-density at its draws.

required

Returns:

Type Description
NumericArray or NumericArrayBatch

The unnormalized log-density, or one per element of a batch value, labeled log and d's notation, as log prior(mu), under the output unnormalized_log_prob.

Raises:

Type Description
ApplicabilityError

If value does not conform to the event spec.

ResolutionError

If d does not claim SupportsUnnormalizedLogProb.

Source code in probpipe/operations/_density.py
@operation(result=_unnormalized_log_prob_result)
def unnormalized_log_prob(d: Distribution, value):
    """The log-density of *value* under *d* up to an additive constant.

    Parameters
    ----------
    d : Distribution
        A law claiming ``SupportsUnnormalizedLogProb``.
    value : Any
        One value conforming to ``d.event_spec.term_spec``, or a batch of them. A law
        over such values lifts the call, which then returns the law of the
        log-density at its draws.

    Returns
    -------
    NumericArray or NumericArrayBatch
        The unnormalized log-density, or one per element of a batch value,
        labeled ``log`` and *d*'s notation, as ``log prior(mu)``, under the
        output ``unnormalized_log_prob``.

    Raises
    ------
    ApplicabilityError
        If *value* does not conform to the event spec.
    ResolutionError
        If *d* does not claim ``SupportsUnnormalizedLogProb``.
    """

prob(d, value)

The density of value under d, defined as exp ∘ log_prob.

Parameters:

Name Type Description Default
d Distribution

A law claiming SupportsLogProb, or any other law that log_prob has a route for.

required
value Any

One value conforming to d.event_spec.term_spec, or a batch of them. A law over such values lifts the call, which then returns the law of the density at its draws.

required

Returns:

Type Description
NumericArray or NumericArrayBatch

The density, or one per element of a batch value, labeled by d's notation, as prior(mu), under the output prob.

Raises:

Type Description
ApplicabilityError

If value does not conform to the event spec.

ResolutionError

If log_prob has no route for d.

Source code in probpipe/operations/_density.py
@operation(result=_prob_result, derived_route_check=_log_prob_applies)
def prob(d: Distribution, value):
    """The density of *value* under *d*, defined as ``exp ∘ log_prob``.

    Parameters
    ----------
    d : Distribution
        A law claiming ``SupportsLogProb``, or any other law that ``log_prob``
        has a route for.
    value : Any
        One value conforming to ``d.event_spec.term_spec``, or a batch of them. A law
        over such values lifts the call, which then returns the law of the
        density at its draws.

    Returns
    -------
    NumericArray or NumericArrayBatch
        The density, or one per element of a batch value, labeled by *d*'s
        notation, as ``prior(mu)``, under the output ``prob``.

    Raises
    ------
    ApplicabilityError
        If *value* does not conform to the event spec.
    ResolutionError
        If ``log_prob`` has no route for *d*.
    """
    return jnp.exp(log_prob.using(raw=True)(d, value))

unnormalized_prob(d, value)

The density of value under d up to a factor, defined as exp ∘ unnormalized_log_prob.

Parameters:

Name Type Description Default
d Distribution

A law claiming SupportsUnnormalizedLogProb, or any other law that unnormalized_log_prob has a route for.

required
value Any

One value conforming to d.event_spec.term_spec, or a batch of them. A law over such values lifts the call, which then returns the law of the unnormalized density at its draws.

required

Returns:

Type Description
NumericArray or NumericArrayBatch

The unnormalized density, or one per element of a batch value, labeled by d's notation, as prior(mu), under the output unnormalized_prob.

Raises:

Type Description
ApplicabilityError

If value does not conform to the event spec.

ResolutionError

If unnormalized_log_prob has no route for d.

Source code in probpipe/operations/_density.py
@operation(result=_unnormalized_prob_result, derived_route_check=_unnormalized_log_prob_applies)
def unnormalized_prob(d: Distribution, value):
    """The density of *value* under *d* up to a factor, defined as ``exp ∘ unnormalized_log_prob``.

    Parameters
    ----------
    d : Distribution
        A law claiming ``SupportsUnnormalizedLogProb``, or any other law that
        ``unnormalized_log_prob`` has a route for.
    value : Any
        One value conforming to ``d.event_spec.term_spec``, or a batch of them. A law
        over such values lifts the call, which then returns the law of the
        unnormalized density at its draws.

    Returns
    -------
    NumericArray or NumericArrayBatch
        The unnormalized density, or one per element of a batch value, labeled
        by *d*'s notation, as ``prior(mu)``, under the output
        ``unnormalized_prob``.

    Raises
    ------
    ApplicabilityError
        If *value* does not conform to the event spec.
    ResolutionError
        If ``unnormalized_log_prob`` has no route for *d*.
    """
    return jnp.exp(unnormalized_log_prob.using(raw=True)(d, value))

random_log_prob(M)

The law of x ↦ log D(x) for D ~ M, a random function.

The density at a point is that random function called at the point, so the operation takes no value.

Parameters:

Name Type Description Default
M Distribution

A random measure, which is a law whose draws D are distributions.

required

Returns:

Type Description
Distribution

A random function over log-densities.

Raises:

Type Description
ResolutionError

If M does not claim SupportsRandomLogProb.

Source code in probpipe/operations/_density.py
@operation(result=_random_log_prob_result)
def random_log_prob(M: Distribution):
    """The law of ``x ↦ log D(x)`` for ``D ~ M``, a random function.

    The density at a point is that random function called at the point, so the
    operation takes no value.

    Parameters
    ----------
    M : Distribution
        A random measure, which is a law whose draws ``D`` are distributions.

    Returns
    -------
    Distribution
        A random function over log-densities.

    Raises
    ------
    ResolutionError
        If *M* does not claim ``SupportsRandomLogProb``.
    """

random_unnormalized_log_prob(M)

The law of x ↦ log D̃(x) for D ~ M, with D̃ the unnormalized density of D.

Parameters:

Name Type Description Default
M Distribution

A random measure, which is a law whose draws D are distributions.

required

Returns:

Type Description
Distribution

A random function over unnormalized log-densities.

Raises:

Type Description
ResolutionError

If M does not claim SupportsRandomUnnormalizedLogProb.

Source code in probpipe/operations/_density.py
@operation(result=_random_unnormalized_log_prob_result)
def random_unnormalized_log_prob(M: Distribution):
    """The law of ``x ↦ log D̃(x)`` for ``D ~ M``, with ``D̃`` the unnormalized density of ``D``.

    Parameters
    ----------
    M : Distribution
        A random measure, which is a law whose draws ``D`` are distributions.

    Returns
    -------
    Distribution
        A random function over unnormalized log-densities.

    Raises
    ------
    ResolutionError
        If *M* does not claim ``SupportsRandomUnnormalizedLogProb``.
    """

Moments and expectations

mean(d)

The mean 𝔼[X] for X ~ d, a value shaped like one draw.

A record-drawing law's mean is a Record with the law's schema, a random function's is its mean function, and a random measure's is the marginalized law. A batch-valued law's mean is elementwise: a batch on the event's levels whose element at each position is the mean of the draw's element there.

The routes, in selection order, are the law's closed form, closed_form; by_output, which computes each output of a record event by the route its own view selects; and the Monte Carlo fallback, monte_carlo. A dependent joint claims no mean, so when one of its outputs, such as a root factor, has an exact mean, its mean takes by_output: that output's mean is exact, and the result as a whole is approximate.

Parameters:

Name Type Description Default
d Distribution

The law, whose _mean gives the closed form, whose outputs' views give their own means otherwise, and whose draws the Monte Carlo fallback averages.

required

Returns:

Type Description
TrackedTerm

The mean at the law's declared event kind, labeled 𝔼[(mu, tau) ~ d] for a law d over mu and tau.

Raises:

Type Description
ResolutionError

If d has no closed-form mean and does not sample, or, under exact_only, if an output of a record event has no exact mean.

MathematicalDomainError

If the mean of d, or of an output whose own route is exact, is known to be undefined, as a Cauchy law's is.

Source code in probpipe/operations/_moments.py
@operation(result=_mean_result)
def mean(d: Distribution):
    """The mean ``𝔼[X]`` for ``X ~ d``, a value shaped like one draw.

    A record-drawing law's mean is a ``Record`` with the law's schema, a random
    function's is its mean function, and a random measure's is the
    marginalized law. A batch-valued law's mean is elementwise: a batch on the
    event's levels whose element at each position is the mean of the draw's
    element there.

    The routes, in selection order, are the law's closed form,
    ``closed_form``; ``by_output``, which computes each output of a
    record event by the route its own view selects; and the Monte
    Carlo fallback, ``monte_carlo``. A dependent joint claims no mean, so when
    one of its outputs, such as a root factor, has an exact mean, its mean
    takes ``by_output``: that output's mean is exact, and the result as
    a whole is approximate.

    Parameters
    ----------
    d : Distribution
        The law, whose ``_mean`` gives the closed form, whose outputs' views
        give their own means otherwise, and whose draws the Monte Carlo
        fallback averages.

    Returns
    -------
    TrackedTerm
        The mean at the law's declared event kind, labeled ``𝔼[(mu, tau) ~ d]``
        for a law ``d`` over ``mu`` and ``tau``.

    Raises
    ------
    ResolutionError
        If *d* has no closed-form mean and does not sample, or, under
        ``exact_only``, if an output of a record event has no exact mean.
    MathematicalDomainError
        If the mean of *d*, or of an output whose own route is exact, is
        known to be undefined, as a Cauchy law's is.
    """

variance(d)

The variance of X ~ d, a value shaped like one draw.

A batch-valued law's variance is elementwise, as its mean is. The routes are those of mean: the closed form, closed_form; by_output, which computes each output of a record event by the route its own view selects; and the Monte Carlo fallback, monte_carlo.

Parameters:

Name Type Description Default
d Distribution

The law, whose _variance gives the closed form, whose outputs' views give their own variances otherwise, and whose draws the Monte Carlo fallback uses.

required

Returns:

Type Description
TrackedTerm

The variance at the law's declared event kind, with non-negative leaves, labeled 𝕍[(mu, tau) ~ d].

Raises:

Type Description
ApplicabilityError

If the event is measure-valued, which has no event-typed variance in general.

ResolutionError

If d has no closed-form variance and does not sample, or, under exact_only, if an output of a record event has no exact variance.

MathematicalDomainError

If the variance of d, or of an output whose own route is exact, is known to be undefined, as a Cauchy law's is.

Source code in probpipe/operations/_moments.py
@operation(result=_variance_result, applicability_checks=(_event_typed_variance,))
def variance(d: Distribution):
    """The variance of ``X ~ d``, a value shaped like one draw.

    A batch-valued law's variance is elementwise, as its mean is. The routes
    are those of ``mean``: the closed form, ``closed_form``;
    ``by_output``, which computes each output of a record event by the
    route its own view selects; and the Monte Carlo fallback,
    ``monte_carlo``.

    Parameters
    ----------
    d : Distribution
        The law, whose ``_variance`` gives the closed form, whose outputs'
        views give their own variances otherwise, and whose draws the Monte
        Carlo fallback uses.

    Returns
    -------
    TrackedTerm
        The variance at the law's declared event kind, with non-negative
        leaves, labeled ``𝕍[(mu, tau) ~ d]``.

    Raises
    ------
    ApplicabilityError
        If the event is measure-valued, which has no event-typed variance in
        general.
    ResolutionError
        If *d* has no closed-form variance and does not sample, or, under
        ``exact_only``, if an output of a record event has no exact variance.
    MathematicalDomainError
        If the variance of *d*, or of an output whose own route is exact, is
        known to be undefined, as a Cauchy law's is.
    """

standard_deviation(d)

The standard deviation sqrt(variance(d)) of X ~ d, a value shaped like one draw.

Each coordinate's standard deviation is the square root of its variance, so a record-drawing law's is a Record with a field for each output, and a random function's is its pointwise standard deviation function.

The call takes the routes of variance: its closed form, its by_output route, and its Monte Carlo fallback. exact_only, max_evaluations, and num_samples set on this operation pass to variance, but method does not, so a route of variance is chosen on variance.using(method=...). When variance draws Monte Carlo samples, the call's provenance records their number as num_samples.

Parameters:

Name Type Description Default
d Distribution

The law, whose variance the call takes.

required

Returns:

Type Description
TrackedTerm

The standard deviation at the law's declared event kind, with non-negative leaves under the event's outputs, labeled √𝕍[(mu, tau) ~ d].

Raises:

Type Description
ApplicabilityError

If the event is measure-valued, which has no event-typed variance in general.

ResolutionError

If variance has no route for d, or, under exact_only, no exact route.

MathematicalDomainError

If the variance of d is known to be undefined, as a Cauchy law's is.

Source code in probpipe/operations/_moments.py
@operation(
    result=_standard_deviation_result,
    applicability_checks=(_event_typed_variance,),
    derived_route_check=_variance_applies,
)
def standard_deviation(d: Distribution):
    """The standard deviation ``sqrt(variance(d))`` of ``X ~ d``, a value shaped like one draw.

    Each coordinate's standard deviation is the square root of its variance,
    so a record-drawing law's is a ``Record`` with a field for each output,
    and a random function's is its pointwise standard deviation function.

    The call takes the routes of ``variance``: its closed form, its
    ``by_output`` route, and its Monte Carlo fallback. ``exact_only``,
    ``max_evaluations``, and ``num_samples`` set on this operation pass to
    ``variance``, but ``method`` does not, so a route of ``variance`` is chosen
    on ``variance.using(method=...)``. When ``variance`` draws Monte Carlo
    samples, the call's provenance records their number as ``num_samples``.

    Parameters
    ----------
    d : Distribution
        The law, whose variance the call takes.

    Returns
    -------
    TrackedTerm
        The standard deviation at the law's declared event kind, with
        non-negative leaves under the event's outputs, labeled
        ``√𝕍[(mu, tau) ~ d]``.

    Raises
    ------
    ApplicabilityError
        If the event is measure-valued, which has no event-typed variance in
        general.
    ResolutionError
        If ``variance`` has no route for *d*, or, under ``exact_only``, no exact
        route.
    MathematicalDomainError
        If the variance of *d* is known to be undefined, as a Cauchy law's is.
    """
    return _root(variance.using(raw=True)(d))

cov(d1, d2=None)

The covariance of the flattened draw of X1 ~ d1, or the cross-covariance of X1 and X2 ~ d2.

The flattened draw ravels each array leaf in row-major order and concatenates the leaves in the record's canonical order. A batch-valued draw is raveled in its raw form, so each leaf runs over the event's batch axes and then the element's own axes.

cov(d1, d2) is Cov(X1, X2) = E[(X1 - E X1)(X2 - E X2)ᵀ], with the two laws drawn as a lift draws them: two laws that read one law's draws, such as two coupled marginals d["y"] and d["x"], are drawn together, and two unrelated laws are drawn independently, so their block is zero. It is the block of rows X1 and columns X2 of the covariance of the two draws taken together, which is the off-diagonal block of the matrix that numpy.cov returns for the stacked draws. An omitted d2, or d2 that is d1 itself, gives the covariance of d1.

Two laws whose draws are coordinates of one law's draws, as coupled marginals, copies, and renames of one law are, take coupled_marginals, which takes the covariance of that law's coupled marginal at those coordinates, exact when its covariance is. Two unrelated laws take independent, an exact zero. Other laws drawn together, such as a transform of a coupled marginal and its parent, take joint_lift, which takes the covariance of the law of the pair of their draws, exact when the lift enumerates an empirical law's atoms. That lift draws at most max_evaluations pairs, as pushforward does, so cov.using(max_evaluations=n) sets the number of draws of its estimate.

Parameters:

Name Type Description Default
d1 Distribution

A law with a numeric event, whose draws give the rows.

required
d2 Distribution

A second law with a numeric event, whose draws give the columns.

None

Returns:

Type Description
NumericArray

The dense (size of d1, size of d2) covariance over the events' coordinates in canonical order, labeled ℂ[(mu, tau) ~ d] for one law and ℂ[y ~ d, x ~ d] for two.

Raises:

Type Description
ApplicabilityError

If an event is not numeric.

ResolutionError

If d1 has no closed-form covariance and does not sample, if two laws have no route, or if d1 and d2 are drawn independently but share a law, as (a & b)["a"] and a do.

Examples:

>>> import jax.numpy as jnp
>>> from probpipe import MultivariateNormal
>>> d = MultivariateNormal("v", loc=jnp.zeros(2), cov=jnp.array([[2.0, 0.5], [0.5, 1.0]]))
>>> cov(d).raw.tolist()
[[2.0, 0.5], [0.5, 1.0]]
Source code in probpipe/operations/_moments.py
@operation(
    result=_cov_result,
    applicability_checks=(_numeric_events,),
    roles={"d2": (DistributionSpec,)},
)
def cov(d1: Distribution, d2: Distribution | None = None):
    """The covariance of the flattened draw of ``X1 ~ d1``, or the cross-covariance of ``X1`` and ``X2 ~ d2``.

    The flattened draw ravels each array leaf in row-major order and
    concatenates the leaves in the record's canonical order. A batch-valued
    draw is raveled in its raw form, so each leaf runs over the event's batch
    axes and then the element's own axes.

    ``cov(d1, d2)`` is ``Cov(X1, X2) = E[(X1 - E X1)(X2 - E X2)ᵀ]``, with the two
    laws drawn as a lift draws them: two laws that read one law's draws, such
    as two coupled marginals ``d["y"]`` and ``d["x"]``, are drawn together, and
    two unrelated laws are drawn independently, so their block is zero. It is
    the block of rows ``X1`` and columns ``X2`` of the covariance of the two
    draws taken together, which is the off-diagonal block of the matrix that
    ``numpy.cov`` returns for the stacked draws. An omitted *d2*,
    or ``d2`` that is *d1* itself, gives the covariance of *d1*.

    Two laws whose draws are coordinates of one law's draws, as coupled
    marginals, copies, and renames of one law are, take ``coupled_marginals``,
    which takes the covariance of that law's coupled marginal at those
    coordinates, exact when its covariance is. Two unrelated laws take
    ``independent``, an exact zero. Other laws drawn together, such as a
    transform of a coupled marginal and its parent, take ``joint_lift``,
    which takes the covariance of the law of the pair of their draws, exact
    when the lift enumerates an empirical law's atoms. That lift draws at most
    ``max_evaluations`` pairs, as ``pushforward`` does, so
    ``cov.using(max_evaluations=n)`` sets the number of draws of its estimate.

    Parameters
    ----------
    d1 : Distribution
        A law with a numeric event, whose draws give the rows.
    d2 : Distribution, optional
        A second law with a numeric event, whose draws give the columns.

    Returns
    -------
    NumericArray
        The dense ``(size of d1, size of d2)`` covariance over the events'
        coordinates in canonical order, labeled ``ℂ[(mu, tau) ~ d]`` for one
        law and ``ℂ[y ~ d, x ~ d]`` for two.

    Raises
    ------
    ApplicabilityError
        If an event is not numeric.
    ResolutionError
        If *d1* has no closed-form covariance and does not sample, if two laws
        have no route, or if *d1* and *d2* are drawn independently but share a
        law, as ``(a & b)["a"]`` and ``a`` do.

    Examples
    --------
    >>> import jax.numpy as jnp
    >>> from probpipe import MultivariateNormal
    >>> d = MultivariateNormal("v", loc=jnp.zeros(2), cov=jnp.array([[2.0, 0.5], [0.5, 1.0]]))
    >>> cov(d).raw.tolist()
    [[2.0, 0.5], [0.5, 1.0]]
    """

quantile(d, q)

The per-coordinate quantiles of X ~ d at the levels q.

A batch-valued law's quantiles are elementwise, as its mean is. The routes are the law's closed form, closed_form; by_output, which computes each output of a record event by the route its own view selects; and the Monte Carlo fallback, monte_carlo, which using(method=...) selects among. The fallback's quantile at a level q is the generalized inverse inf{x : F(x) >= q} of each coordinate's CDF over the draws, as an empirical law's is.

Parameters:

Name Type Description Default
d Distribution

A law with a numeric event.

required
q float or array of float

One level in [0, 1], or an array of them.

required

Returns:

Type Description
TrackedTerm

For one level, a value of the event's kind; for several, the batch of those values on a level named quantile, before any levels of a batch-valued event. It is labeled ℚ[mu ~ d].

Raises:

Type Description
ApplicabilityError

If the event is not numeric, or q is not numeric.

MathematicalDomainError

If a concrete level lies outside [0, 1].

ResolutionError

If d has no closed-form quantiles and does not sample, or, under exact_only, if an output of a record event has no exact quantiles.

Source code in probpipe/operations/_moments.py
@operation(result=_quantile_result, applicability_checks=(_numeric_event,))
def quantile(d: Distribution, q: Any):
    """The per-coordinate quantiles of ``X ~ d`` at the levels *q*.

    A batch-valued law's quantiles are elementwise, as its mean is. The routes
    are the law's closed form, ``closed_form``; ``by_output``,
    which computes each output of a record event by the route its own
    view selects; and the Monte Carlo fallback, ``monte_carlo``,
    which ``using(method=...)`` selects among. The fallback's quantile
    at a level ``q`` is the generalized
    inverse ``inf{x : F(x) >= q}`` of each coordinate's CDF over the draws, as
    an empirical law's is.

    Parameters
    ----------
    d : Distribution
        A law with a numeric event.
    q : float or array of float
        One level in ``[0, 1]``, or an array of them.

    Returns
    -------
    TrackedTerm
        For one level, a value of the event's kind; for several, the batch of
        those values on a level named ``quantile``, before any levels of a
        batch-valued event. It is labeled ``ℚ[mu ~ d]``.

    Raises
    ------
    ApplicabilityError
        If the event is not numeric, or *q* is not numeric.
    MathematicalDomainError
        If a concrete level lies outside ``[0, 1]``.
    ResolutionError
        If *d* has no closed-form quantiles and does not sample, or, under
        ``exact_only``, if an output of a record event has no exact
        quantiles.
    """

expectation(d, f, fixed_args=None)

The expectation 𝔼[f(X)] for X ~ d, defined as mean(pushforward(d, f)).

The integrand receives one draw of d at a time, whatever its parameter's annotation, on every route. A law claiming SupportsExpectation computes the expectation in closed form, and otherwise the route pushforward_mean builds the pushforward by an evaluation rule, which using(method=...) names, and takes its mean. Under exact_only both steps are restricted to exact routes. The pushforward evaluates the integrand at most max_evaluations times, as pushforward(d, f) does, so expectation.using(max_evaluations=n) sets the number of draws of a Monte Carlo estimate, and the call's provenance records the draws it took as num_samples.

Parameters:

Name Type Description Default
d Distribution

The law to integrate against.

required
f callable or Function

Maps one draw to a value; a Function's output spec names the result's kind. Exactly one of its parameters has no default and is absent from fixed_args, and each draw binds it.

required
fixed_args mapping of str to Any

The other parameters of a map with several, by name. Each is a constant: a law the direct call would sample, or a batch it would sweep, is refused, including arguments set through the map's construction bind. mean(function(f)(x=d, a=A)) integrates over the law A as well, and function(lambda a: expectation(d, f, {"a": a}))(A) is the law of the expectation at a draw of A.

None

Returns:

Type Description
TrackedTerm

𝔼[f(X)] at the kind the integrand's output spec names, labeled 𝔼[f(mu ~ d)] by the integrand's label: a Function's label, a callable's __name__, and 𝒻 for a lambda.

Raises:

Type Description
ApplicabilityError

If f is not a callable, fixed_args leaves other than one of its parameters open, the open parameter's declaration does not admit a draw of d, or a fixed argument is a law or a batch the call would lift.

ResolutionError

If neither the closed form nor an evaluation rule applies, or, under exact_only, either step has no exact route.

Source code in probpipe/operations/_moments.py
@operation(
    result=_expectation_result,
    roles={"f": (FunctionSpec,)},
    applicability_checks=_integrand_applicability_checks("expectation"),
    derived_route=_PushforwardMean(),
)
def expectation(d: Distribution, f: Any, fixed_args: Mapping[str, Any] | None = None):
    """The expectation ``𝔼[f(X)]`` for ``X ~ d``, defined as ``mean(pushforward(d, f))``.

    The integrand receives one draw of *d* at a time, whatever its parameter's
    annotation, on every route. A law claiming ``SupportsExpectation`` computes
    the expectation in closed form, and otherwise the route ``pushforward_mean``
    builds the pushforward by an evaluation rule, which
    ``using(method=...)`` names, and takes its mean. Under ``exact_only``
    both steps are restricted to exact routes. The pushforward evaluates the
    integrand at most ``max_evaluations`` times, as ``pushforward(d, f)`` does,
    so ``expectation.using(max_evaluations=n)`` sets the number of draws of a
    Monte Carlo estimate, and the call's provenance records the draws it took
    as ``num_samples``.

    Parameters
    ----------
    d : Distribution
        The law to integrate against.
    f : callable or Function
        Maps one draw to a value; a ``Function``'s output spec names the
        result's kind. Exactly one of its parameters has no default and is
        absent from *fixed_args*, and each draw binds it.
    fixed_args : mapping of str to Any, optional
        The other parameters of a map with several, by name. Each is a
        constant: a law the direct call would sample, or a batch it would
        sweep, is refused, including arguments set through the map's
        construction ``bind``. ``mean(function(f)(x=d, a=A))`` integrates over the
        law ``A`` as well, and ``function(lambda a: expectation(d, f, {"a": a}))(A)``
        is the law of the expectation at a draw of ``A``.

    Returns
    -------
    TrackedTerm
        ``𝔼[f(X)]`` at the kind the integrand's output spec names,
        labeled ``𝔼[f(mu ~ d)]`` by the integrand's label: a ``Function``'s
        label, a callable's ``__name__``, and ``𝒻`` for a lambda.

    Raises
    ------
    ApplicabilityError
        If *f* is not a callable, *fixed_args* leaves other than one of its
        parameters open, the open parameter's declaration does not admit a draw
        of *d*, or a fixed argument is a law or a batch the call would lift.
    ResolutionError
        If neither the closed form nor an evaluation rule applies, or, under
        ``exact_only``, either step has no exact route.
    """
    return mean(pushforward(d, f, fixed_args))

Summary tables

summarize collects several of the moments above for one law in one record, which displays as a table. It is a function over the operations, so it has no routes of its own.

summarize(d, *statistics, interval=0.8, mcse=False)

Summarize a law in a record of standard summaries, which displays as a table.

The result is a NumericRecord nested by statistic: each top-level field is the term that the statistic returns for d, over the law's event paths, so summarize(d)["sd/mu"] is the standard deviation of mu. A law of one whole term holds each statistic under its output, as mean/theta. The record displays as a table with one row for each path and one column for each statistic, under the label summary of and the law's notation. The line below the table states how each statistic was computed: exact, Monte Carlo with its draws, or approximate, as the statistic's provenance records it, and, for an MCMC posterior, MCMC with its chains and draws. The record's provenance records those descriptions. pd.DataFrame(summarize(d).raw) gives the table of a law whose outputs are scalars as a DataFrame.

The default columns are:

  • mean: mean(d);
  • sd: standard_deviation(d);
  • median: quantile(d, 0.5);
  • the ends of the central interval of probability interval, as q10 and q90 for 0.8: quantile(d, (1 - interval) / 2) and quantile(d, (1 + interval) / 2).

A posterior whose draws lie on the levels chain and draw, as an MCMC method returns it, also has the columns r_hat, ess_bulk, and ess_tail, computed as add_mcmc_diagnostics computes them and keyed by the same paths. The posterior's annotations are left as they are.

With mcse=True, each statistic gains a column mcse_<name> of its Monte Carlo standard error, after the statistic columns:

  1. An MCMC posterior: each statistic of its draws estimates the posterior the sampler targets, so each column holds the ArviZ standard error of its kind: mean, sd, median, or the quantile at its probability. A statistic of another kind has nan.
  2. Another law: a path that the statistic's route computed exactly has 0. For mean, a path its route drew n draws of has sd / sqrt(n). Any other path has nan, since its standard error needs the draws the route took.

Parameters:

Name Type Description Default
d Distribution or DistributionBatch

The law to summarize. A DistributionBatch gives a batch of summary records, one for each law, on the batch's levels. A column that only some laws give, as r_hat of a batch that mixes MCMC posteriors with other laws, holds nan for the others.

required
*statistics callable or Mapping of str to callable

The columns to compute in place of the default ones, each a callable that takes d, such as an operation. A callable is named by its label, as mean and variance are, or by its __name__, and the name must be an identifier. A mapping names its callables by its keys, as {"sd": standard_deviation} does.

()
interval float

The probability of the central interval whose ends the default columns hold, strictly between 0 and 1. It does not apply to given statistics.

0.8
mcse bool

Whether to add the Monte Carlo standard error columns.

False

Returns:

Type Description
NumericRecord or NumericRecordBatch

The summary record labeled summary of and the law's notation, with one top-level field for each column, or, for a DistributionBatch, the batch of the summary records of its laws.

Raises:

Type Description
TypeError

If d is not a Distribution or a DistributionBatch, interval is not a real number, a statistic is neither a callable nor a mapping of names to callables, or a statistic returns a value that is not numeric over the law's outputs.

ValueError

If interval is not strictly between 0 and 1, a callable's name is not an identifier, a name is empty, has /, or names another statistic, two statistics return values over different paths or shapes, a batch holds no law, or the laws of a batch give a column over different paths or shapes.

Examples:

>>> from probpipe import Gamma, Normal, summarize
>>> s = summarize(((Normal("mu", 0.0, 2.0) & Gamma("tau", 2.0, 1.0))).with_label("model"))
>>> s.label
'summary of model(mu, tau)'
>>> float(s["sd/mu"])
2.0
Source code in probpipe/diagnostics/_summary.py
def summarize(
    d: Distribution | DistributionBatch,
    *statistics: Callable[[Any], Any] | Mapping[str, Callable[[Any], Any]],
    interval: float = 0.8,
    mcse: bool = False,
) -> NumericRecord | NumericRecordBatch:
    """Summarize a law in a record of standard summaries, which displays as a table.

    The result is a ``NumericRecord`` nested by statistic: each top-level field
    is the term that the statistic returns for *d*, over the law's event paths,
    so ``summarize(d)["sd/mu"]`` is the standard deviation of ``mu``. A law of
    one whole term holds each statistic under its output, as ``mean/theta``.
    The record displays as a table with one row for each path and one column
    for each statistic, under the label ``summary of`` and the law's notation.
    The line below the table states how each statistic was computed:
    ``exact``, ``Monte Carlo`` with its draws, or ``approximate``, as the
    statistic's provenance records it, and, for an MCMC posterior, ``MCMC``
    with its chains and draws. The record's provenance records those
    descriptions. ``pd.DataFrame(summarize(d).raw)`` gives the table of a law
    whose outputs are scalars as a DataFrame.

    The default columns are:

    - ``mean``: ``mean(d)``;
    - ``sd``: ``standard_deviation(d)``;
    - ``median``: ``quantile(d, 0.5)``;
    - the ends of the central interval of probability *interval*, as ``q10`` and
      ``q90`` for ``0.8``: ``quantile(d, (1 - interval) / 2)`` and
      ``quantile(d, (1 + interval) / 2)``.

    A posterior whose draws lie on the levels ``chain`` and ``draw``, as an MCMC
    method returns it, also has the columns ``r_hat``, ``ess_bulk``, and
    ``ess_tail``, computed as ``add_mcmc_diagnostics`` computes them and keyed by
    the same paths. The posterior's annotations are left as they are.

    With ``mcse=True``, each statistic gains a column ``mcse_<name>`` of its
    Monte Carlo standard error, after the statistic columns:

    1. **An MCMC posterior:** each statistic of its draws estimates the posterior
       the sampler targets, so each column holds the ArviZ standard error of
       its kind: ``mean``, ``sd``, ``median``, or the quantile at its
       probability. A statistic of another kind has ``nan``.
    2. **Another law:** a path that the statistic's route computed exactly has
       ``0``. For ``mean``, a path its route drew ``n`` draws of has
       ``sd / sqrt(n)``. Any other path has ``nan``, since its standard error
       needs the draws the route took.

    Parameters
    ----------
    d : Distribution or DistributionBatch
        The law to summarize. A ``DistributionBatch`` gives a batch of summary
        records, one for each law, on the batch's levels. A column that only
        some laws give, as ``r_hat`` of a batch that mixes MCMC posteriors with
        other laws, holds ``nan`` for the others.
    *statistics : callable or Mapping of str to callable
        The columns to compute in place of the default ones, each a callable
        that takes *d*, such as an operation. A callable is named by its label,
        as ``mean`` and ``variance`` are, or by its ``__name__``, and the name
        must be an identifier. A mapping names its callables by its keys, as
        ``{"sd": standard_deviation}`` does.
    interval : float
        The probability of the central interval whose ends the default columns
        hold, strictly between 0 and 1. It does not apply to given statistics.
    mcse : bool
        Whether to add the Monte Carlo standard error columns.

    Returns
    -------
    NumericRecord or NumericRecordBatch
        The summary record labeled ``summary of`` and the law's notation, with one
        top-level field for each column, or, for a ``DistributionBatch``, the
        batch of the summary records of its laws.

    Raises
    ------
    TypeError
        If *d* is not a ``Distribution`` or a ``DistributionBatch``, *interval* is
        not a real number, a statistic is neither a callable nor a mapping of
        names to callables, or a statistic returns a value that is not numeric
        over the law's outputs.
    ValueError
        If *interval* is not strictly between 0 and 1, a callable's name is not
        an identifier, a name is empty, has ``/``, or names another statistic,
        two statistics return values over different paths or shapes, a batch
        holds no law, or the laws of a batch give a column over different paths
        or shapes.

    Examples
    --------
    >>> from probpipe import Gamma, Normal, summarize
    >>> s = summarize(((Normal("mu", 0.0, 2.0) & Gamma("tau", 2.0, 1.0))).with_label("model"))
    >>> s.label
    'summary of model(mu, tau)'
    >>> float(s["sd/mu"])
    2.0
    """
    if not isinstance(d, (Distribution, DistributionBatch)):
        raise TypeError(
            f"summarize: d must be a Distribution or a DistributionBatch, got {type_name(d)}"
        )
    if isinstance(interval, bool) or not isinstance(interval, Real):
        raise TypeError(f"summarize: interval must be a number, got {type_name(interval)}")
    if not 0.0 < float(interval) < 1.0:
        raise ValueError(f"summarize: interval must be strictly between 0 and 1, got {interval}")
    chosen = _given_statistics(statistics) if statistics else _default_statistics(float(interval))
    if isinstance(d, DistributionBatch):
        return _summary_batch(d, chosen, mcse)
    record, computations = _summary(d, chosen, mcse)
    return record.with_provenance(_summary_provenance(d, computations))

Conditioning

condition_on(d, given)

Fix fields of d at the values given holds, and return the resulting law, normalized.

The exact stage binds inputs, calls a conditioning capability, or forms the unnormalized conditional of the produced fields, and the normalization stage passes an unnormalized result to the inference-method registry. using(method="unnormalized") returns the exact stage's result as it is, and using(exact_only=True) raises rather than normalize by an approximate method. A batch of givens is swept: each element is conditioned on as one given is, and the results form a batch on the givens' levels.

Parameters:

Name Type Description Default
d Distribution or ConditionalDistribution

The law or kernel to condition.

required
given Record, Mapping, or RecordBatch

The values, keyed by field path: inputs of a kernel, or fields the law produces; or a batch of such values. A path into a structured given input binds that node and leaves the other fields in the residual input; binding its last field dissolves the input. Paths must not overlap, and all values bind shared symbolic dimensions together.

required

Returns:

Type Description
Distribution, ConditionalDistribution, or DistributionBatch

The conditional, normalized: an ordinary law once every input is bound, and otherwise a kernel over the inputs left whose laws are normalized; for a batch of givens, the batch of the conditionals. It keeps d's label, except that fixing the whole events of factors upstream of the rest gives the labels of the factors left, and it holds the conditioned paths fixed after any that d holds, so a posterior of model given y displays as model(mu; y).

Raises:

Type Description
ApplicabilityError

If d is neither distribution kind.

ResolutionError

If no route applies under the controls, including an exact stage whose result is unnormalized under exact_only.

Source code in probpipe/operations/_condition.py
@operation(
    result=_condition_on_result,
    roles={"d": (DistributionSpec, ConditionalDistributionSpec), "given": _GIVEN_KINDS},
)
def condition_on(d: Distribution, given: Record | Mapping[str, Any]):
    """Fix fields of *d* at the values *given* holds, and return the resulting law, normalized.

    The exact stage binds inputs, calls a conditioning capability, or
    forms the unnormalized conditional of the produced fields, and the
    normalization stage passes an unnormalized result to the inference-method
    registry. ``using(method="unnormalized")`` returns the exact stage's
    result as it is, and ``using(exact_only=True)`` raises rather than
    normalize by an approximate method. A batch of givens is swept: each
    element is conditioned on as one given is, and the results form a batch on
    the givens' levels.

    Parameters
    ----------
    d : Distribution or ConditionalDistribution
        The law or kernel to condition.
    given : Record, Mapping, or RecordBatch
        The values, keyed by field path: inputs of a kernel, or fields the
        law produces; or a batch of such values. A path into a structured given
        input binds that node and leaves the other fields in the residual input;
        binding its last field dissolves the input. Paths must not overlap, and
        all values bind shared symbolic dimensions together.

    Returns
    -------
    Distribution, ConditionalDistribution, or DistributionBatch
        The conditional, normalized: an ordinary law once every input is
        bound, and otherwise a kernel over the inputs left whose laws are
        normalized; for a batch of givens, the batch of the conditionals. It
        keeps *d*'s label, except that fixing the whole events of factors
        upstream of the rest gives the labels of the factors left, and it
        holds the conditioned paths fixed after any that *d* holds, so a
        posterior of ``model`` given ``y`` displays as ``model(mu; y)``.

    Raises
    ------
    ApplicabilityError
        If *d* is neither distribution kind.
    ResolutionError
        If no route applies under the controls, including an exact stage whose
        result is unnormalized under ``exact_only``.
    """

Joints, marginals, and mixtures

joint(A, B, **align)

merge A with B after renaming B's fields, as A & B.rename(**align).

The factors are consumed as objects, so a batch of laws is refused rather than swept (VI.11).

Parameters:

Name Type Description Default
A Distribution or ConditionalDistribution

The first factor, which may condition on what B produces, since the factors are merged conditional-first.

required
B Distribution or ConditionalDistribution

The second factor, whose paths align renames.

required
**align str

Renames of B's paths, old=new, as rename takes them.

{}

Returns:

Type Description
Distribution or ConditionalDistribution

The joint; a kernel when a given is left unmet. The joint is unlabeled, as one that & builds is, so its notation joins its factors' notations with ·.

Raises:

Type Description
ApplicabilityError

If a factor is neither distribution kind, a batch of laws included.

ValueError

If merge rejects the realigned factors.

Source code in probpipe/operations/_joint.py
@operation(
    result=_joint_result,
    roles={"A": _FACTOR_KINDS, "B": _FACTOR_KINDS},
)
def joint(A: Any, B: Any, **align: str):
    """merge *A* with *B* after renaming *B*'s fields, as ``A & B.rename(**align)``.

    The factors are consumed as objects, so a batch of laws is refused rather
    than swept (VI.11).

    Parameters
    ----------
    A : Distribution or ConditionalDistribution
        The first factor, which may condition on what *B* produces, since the
        factors are merged conditional-first.
    B : Distribution or ConditionalDistribution
        The second factor, whose paths *align* renames.
    **align : str
        Renames of *B*'s paths, ``old=new``, as ``rename`` takes them.

    Returns
    -------
    Distribution or ConditionalDistribution
        The joint; a kernel when a given is left unmet. The joint is unlabeled,
        as one that ``&`` builds is, so its notation joins its factors'
        notations with ``·``.

    Raises
    ------
    ApplicabilityError
        If a factor is neither distribution kind, a batch of laws included.
    ValueError
        If merge rejects the realigned factors.
    """

marginal(d, paths)

The standalone marginal of d at paths, a standalone law with no reference back to d.

At event paths, marginal(d, paths) is the detached law of d[paths]: one path gives the node there whole under the path's last name, and a list or a tuple of paths a law over the record that keeps each node at its own path, in d's order, so marginal(grouped, ["a", "g/c"]) draws records {a, g: {c}}. A lift draws the marginal independently of d and of the laws d is built from (V.5).

The law's exact marginal capability and whole-event structural route precede the monte_carlo route. That route draws num_samples joint samples once and returns their projected empirical law. Its atoms have uniform weights and remain fixed when the result is sampled again. Set the count with marginal.using(num_samples=4096)(d, paths). The call records its approximation and sample count in provenance.

A selection covering the whole event retains the law independently. For a scalar law with root output y, marginal(d, "y") retains its scalar event, while marginal(d, ["y"]) wraps it in a record under y.

With given=, selection follows the conditional order in VI.0: native exact routes, exact conditioning followed by an exact marginal, then approximate routes and unrestricted conditional delegation. A check reports exact delegation unresolved when it needs the bound law. An explicit method="monte_carlo" selects sampling directly.

The atoms' leading level is sample. For a batch-valued event, underscores are appended until that name differs from the event's levels.

Parameters:

Name Type Description Default
d Distribution

The law.

required
paths str, or list or tuple of str

An event path, whose group selects the fields under it, or a list of event paths.

required

Returns:

Type Description
Distribution

The marginal, which holds the paths d holds fixed. A marginal over the whole events of factors of a joint that condition on nothing outside them is those factors: one factor keeps its own label, and several form a product without a label in the joint's order, as marginal(model, ["a", "b"]) displays as a(a)·b(b). Any other marginal keeps d's label, as marginal(model, "y") displays as model(y). The view d[paths] displays as the marginal does.

Raises:

Type Description
ApplicabilityError

If d is over a record and a path is not one of its paths.

TypeError

If paths is neither a string nor a list or tuple of strings, or d is over a value with no paths, such as an array.

ValueError

If a path is empty or has an empty name, or a list of paths is empty, names a path twice, or holds a path inside another.

ResolutionError

If d has no exact marginal at paths and does not sample.

Source code in probpipe/operations/_marginal.py
@operation(result=_marginal_result)
def marginal(d: Distribution, paths: PathsLike):
    """The standalone marginal of *d* at *paths*, a standalone law with no reference back to *d*.

    At event paths, ``marginal(d, paths)`` is the detached law of ``d[paths]``: one
    path gives the node there whole under the path's last name, and a list or
    a tuple of paths a law over the record that keeps each node at its own
    path, in *d*'s order, so ``marginal(grouped, ["a", "g/c"])`` draws records
    ``{a, g: {c}}``. A lift draws the marginal independently of *d* and of
    the laws *d* is built from (V.5).

    The law's exact marginal capability and whole-event structural route
    precede the ``monte_carlo`` route. That route draws ``num_samples`` joint
    samples once and returns their projected
    empirical law. Its atoms have uniform weights and remain fixed when the
    result is sampled again. Set the count with
    ``marginal.using(num_samples=4096)(d, paths)``. The call records its
    approximation and sample count in provenance.

    A selection covering the whole event retains the law independently.
    For a scalar law with root output ``y``, ``marginal(d, "y")`` retains its
    scalar event, while ``marginal(d, ["y"])`` wraps it in a record under ``y``.

    With ``given=``, selection follows the conditional order in VI.0: native
    exact routes, exact conditioning followed by an exact marginal, then
    approximate routes and unrestricted conditional delegation. A check reports
    exact delegation unresolved when it needs the bound law. An explicit
    ``method="monte_carlo"`` selects sampling directly.

    The atoms' leading level is ``sample``. For a batch-valued event,
    underscores are appended until that name differs from the event's levels.

    Parameters
    ----------
    d : Distribution
        The law.
    paths : str, or list or tuple of str
        An event path, whose group selects the fields under it, or a list of
        event paths.

    Returns
    -------
    Distribution
        The marginal, which holds the paths *d* holds fixed. A marginal over
        the whole events of factors of a joint that condition on nothing
        outside them is those factors: one factor keeps its own label, and
        several form a product without a label in the joint's order, as
        ``marginal(model, ["a", "b"])`` displays as ``a(a)·b(b)``. Any other
        marginal keeps *d*'s label, as ``marginal(model, "y")`` displays as
        ``model(y)``. The view ``d[paths]`` displays as the marginal does.

    Raises
    ------
    ApplicabilityError
        If *d* is over a record and a path is not one of its paths.
    TypeError
        If *paths* is neither a string nor a list or tuple of strings, or *d*
        is over a value with no paths, such as an array.
    ValueError
        If a path is empty or has an empty name, or a list of paths is empty,
        names a path twice, or holds a path inside another.
    ResolutionError
        If *d* has no exact marginal at *paths* and does not sample.
    """

factor(d, output_name)

The complete factor of the joint d that produces the output output_name.

The factor is detached from d, so a lift draws a factor that is a law independently of d and of the laws d is built from (V.5, VI.8).

Parameters:

Name Type Description Default
d Distribution or ConditionalDistribution

A factored joint.

required
output_name str

One of the joint's outputs.

required

Returns:

Type Description
Distribution or ConditionalDistribution

The factor under its own label, a kernel when it conditions on another factor's output.

Raises:

Type Description
ApplicabilityError

If output_name is not an output of d.

ResolutionError

If d exposes no factors.

Source code in probpipe/operations/_marginal.py
@operation(
    result=_factor_result,
    applicability_checks=(_names_an_output,),
    roles={"d": (DistributionSpec, ConditionalDistributionSpec)},
)
def factor(d: Distribution, output_name: str):
    """The complete factor of the joint *d* that produces the output *output_name*.

    The factor is detached from *d*, so a lift draws a factor that is a law
    independently of *d* and of the laws *d* is built from (V.5, VI.8).

    Parameters
    ----------
    d : Distribution or ConditionalDistribution
        A factored joint.
    output_name : str
        One of the joint's outputs.

    Returns
    -------
    Distribution or ConditionalDistribution
        The factor under its own label, a kernel when it conditions on another
        factor's output.

    Raises
    ------
    ApplicabilityError
        If *output_name* is not an output of *d*.
    ResolutionError
        If *d* exposes no factors.
    """

mixture(K, mixing)

The mixture of the kernel K under the mixing distribution mixing.

The mixing distribution's outputs meet the kernel's inputs of the same name. An empirical mixing law is enumerated into a finite MixtureDistribution with its original weights. Otherwise the derived route projects joint draws through pushforward. Its sampling route returns an empirical approximation, with the draw count controlled by max_evaluations.

The finite route builds one component law per atom, so its cost grows with the number of atoms.

Inputs that mixing leaves unfed remain inputs of the returned kernel. Binding its last required input computes the mixture eagerly. Conditional sampling draws from the merged joint and projects its outputs directly.

Parameters:

Name Type Description Default
K ConditionalDistribution

The kernel K(s, ·), which draws T given S = s.

required
mixing Distribution

The law μ of S.

required

Returns:

Type Description
Distribution or ConditionalDistribution

The standalone law or kernel of the kernel's output, with the kernel's event spec.

Raises:

Type Description
ValueError

If the factors' outputs overlap or matched input and output specs do not unify, as in a merge.

ResolutionError

If neither the formula nor a direct route applies.

Source code in probpipe/operations/_mixture.py
@operation(
    # A law keeps K.event_spec; with unfed inputs, the returned kernel declares its spec.
    result=lambda K, mixing: (
        None
        if any(name not in mixing.event_spec.outputs for name in K.given_spec.required)
        else OutputSpec(DistributionSpec(K.event_spec))
    ),
    derived_route_check=lambda K, mixing: pushforward.check(
        K & mixing, _kernel_output_projection(K)
    ),
)
def mixture(K: ConditionalDistribution, mixing: Distribution):
    """The mixture of the kernel *K* under the mixing distribution *mixing*.

    The mixing distribution's outputs meet the kernel's inputs of the same
    name. An empirical mixing law is enumerated into a finite
    ``MixtureDistribution`` with its original weights. Otherwise the derived
    route projects joint draws through ``pushforward``. Its sampling route
    returns an empirical approximation, with the draw count controlled by
    ``max_evaluations``.

    The finite route builds one component law per atom, so its cost grows
    with the number of atoms.

    Inputs that mixing leaves unfed remain inputs of the returned kernel.
    Binding its last required input computes the mixture eagerly. Conditional
    sampling draws from the merged joint and projects its outputs directly.

    Parameters
    ----------
    K : ConditionalDistribution
        The kernel ``K(s, ·)``, which draws ``T`` given ``S = s``.
    mixing : Distribution
        The law ``μ`` of ``S``.

    Returns
    -------
    Distribution or ConditionalDistribution
        The standalone law or kernel of the kernel's output, with the kernel's event
        spec.

    Raises
    ------
    ValueError
        If the factors' outputs overlap or matched input and output specs
        do not unify, as in a merge.
    ResolutionError
        If neither the formula nor a direct route applies.
    """
    return pushforward((K & mixing), _kernel_output_projection(K))

Maps

pushforward(d, f, fixed_args=None)

The law of f(X) for X ~ d, the pushforward f♯d.

The map receives one draw of d at a time, at its one open parameter, whatever that parameter's annotation is, so a parameter annotated Any or Distribution receives draws. The draw is presented as V.5 presents one draw. The direct call f(d) instead passes the law whole to such a parameter. The evaluation rules realize the pushforward, and using(method=...) names one, such as empirical_enumeration or sampling_lift.

A kernel without given returns a kernel with the same inputs. Binding its last required input computes the ordinary pushforward eagerly. Its conditional sampler applies the map directly to source draws. The output spec is inferred abstractly when possible; otherwise the map must declare it. With given, the source is bound before selecting the map's evaluation rule, so a bound finite law retains its exact enumeration route.

Parameters:

Name Type Description Default
d Distribution or ConditionalDistribution

The law or kernel whose draws the map receives. A DistributionBatch gives the batch of the pushforwards of its laws.

required
f callable or Function

The map. Exactly one of its parameters has no default and is absent from fixed_args, and each draw binds it whatever its name.

required
fixed_args mapping of str to Any

The map's other parameters, by name. Each is a constant: a law the direct call would sample, or a batch it would sweep, is refused. This also applies to arguments set through the map's construction bind. The direct call f(x=d, a=A) gives the joint law of the map over both.

None

Returns:

Type Description
Distribution or ConditionalDistribution or DistributionBatch

The law of the map's output, labeled by the map's output label and displayed as the map applied to a draw of d, as f(mu ~ prior). A DistributionBatch operand gives the batch of the pushforwards of its laws, on its levels.

Raises:

Type Description
ApplicabilityError

If d is not a law, fixed_args leaves other than one parameter of f open, the open parameter's declaration does not admit a draw of d, or a fixed argument is a law or a batch the call would lift. A kernel whose output cannot be inferred requires a complete output_spec on the map.

ResolutionError

If no evaluation rule applies.

Source code in probpipe/operations/_pushforward.py
@operation(
    # The returned law or kernel declares the output event.
    result=lambda: None,
    roles={"d": (DistributionSpec, ConditionalDistributionSpec), "f": (FunctionSpec,)},
    applicability_checks=_integrand_applicability_checks("pushforward"),
    # Pushforward takes the map's output label (V.10).
    label=lambda f: _output_label(f, subject="pushforward"),
)
def pushforward(d: Distribution, f: Any, fixed_args: Mapping[str, Any] | None = None):
    """The law of ``f(X)`` for ``X ~ d``, the pushforward ``f♯d``.

    The map receives one draw of *d* at a time, at its one open parameter,
    whatever that parameter's annotation is, so a parameter annotated ``Any`` or
    ``Distribution`` receives draws. The draw is presented as V.5 presents one
    draw. The direct call ``f(d)`` instead passes the law whole to such a
    parameter. The evaluation rules realize the pushforward, and
    ``using(method=...)`` names one, such as ``empirical_enumeration`` or
    ``sampling_lift``.

    A kernel without ``given`` returns a kernel with the same inputs. Binding
    its last required input computes the ordinary pushforward eagerly. Its
    conditional sampler applies the map directly to source draws. The output
    spec is inferred abstractly when possible; otherwise the map must declare it.
    With ``given``, the source is bound before selecting the map's evaluation
    rule, so a bound finite law retains its exact enumeration route.

    Parameters
    ----------
    d : Distribution or ConditionalDistribution
        The law or kernel whose draws the map receives. A ``DistributionBatch`` gives the
        batch of the pushforwards of its laws.
    f : callable or Function
        The map. Exactly one of its parameters has no default and is absent
        from *fixed_args*, and each draw binds it whatever its name.
    fixed_args : mapping of str to Any, optional
        The map's other parameters, by name. Each is a constant: a law the
        direct call would sample, or a batch it would sweep, is refused. This
        also applies to arguments set through the map's construction ``bind``. The
        direct call ``f(x=d, a=A)`` gives the joint law of the map over both.

    Returns
    -------
    Distribution or ConditionalDistribution or DistributionBatch
        The law of the map's output, labeled by the map's output label and
        displayed as the map applied to a draw of *d*, as ``f(mu ~ prior)``.
        A ``DistributionBatch`` operand gives the batch of the pushforwards of
        its laws, on its levels.

    Raises
    ------
    ApplicabilityError
        If *d* is not a law, *fixed_args* leaves other than one parameter of
        *f* open, the open parameter's declaration does not admit a draw of
        *d*, or a fixed argument is a law or a batch the call would lift. A
        kernel whose output cannot be inferred requires a complete
        ``output_spec`` on the map.
    ResolutionError
        If no evaluation rule applies.
    """

inverse(f)

The inverse of the map f, itself invertible with f as its inverse.

Parameters:

Name Type Description Default
f Function

A map that claims SupportsInverse and whose guard admits the inverse, as is_invertible reads them.

required

Returns:

Type Description
Function

The map y ↦ f⁻¹(y), whose label derives from f's.

Raises:

Type Description
ResolutionError

If the inverse is unavailable.

MathematicalDomainError

If f is known to be noninvertible.

Source code in probpipe/operations/_inverse.py
@operation(result=_inverse_result, roles={"f": (FunctionSpec,)})
def inverse(f: Any):
    """The inverse of the map *f*, itself invertible with *f* as its inverse.

    Parameters
    ----------
    f : Function
        A map that claims ``SupportsInverse`` and whose guard admits the
        inverse, as ``is_invertible`` reads them.

    Returns
    -------
    Function
        The map ``y ↦ f⁻¹(y)``, whose label derives from *f*'s.

    Raises
    ------
    ResolutionError
        If the inverse is unavailable.
    MathematicalDomainError
        If *f* is known to be noninvertible.
    """

log_det_jacobian(f, x)

The log-determinant of the Jacobian of the map f at x.

Parameters:

Name Type Description Default
f Function

The map, whose _log_det_jacobian computes the result.

required
x Any

A point of the map's domain.

required

Returns:

Type Description
NumericArray

The scalar log |det J_f(x)|.

Raises:

Type Description
ResolutionError

If f does not claim SupportsLogDetJacobian.

Source code in probpipe/operations/_inverse.py
@operation(result=_log_det_jacobian_result, roles={"f": (FunctionSpec,)})
def log_det_jacobian(f: Any, x: Any):
    """The log-determinant of the Jacobian of the map *f* at *x*.

    Parameters
    ----------
    f : Function
        The map, whose ``_log_det_jacobian`` computes the result.
    x : Any
        A point of the map's domain.

    Returns
    -------
    NumericArray
        The scalar ``log |det J_f(x)|``.

    Raises
    ------
    ResolutionError
        If *f* does not claim ``SupportsLogDetJacobian``.
    """

Errors

ResolutionError

Bases: Exception

No available implementation under the requested controls.

Raised by a registry when no registered method is feasible for the arguments, when the first candidate that is not infeasible is still unresolved, or when the method a caller named is infeasible or not registered.

MathematicalDomainError

Bases: ValueError

The mathematical operation is known to be undefined.

Raised by a method that can establish that its operation is undefined, such as the mean of a Cauchy law.