Skip to content

Continuous Families

The module gives the families of continuous distributions (family registry), each chosen by the values a response can take: a Normal for real values, and other families for positive or bounded supports. A conditional family computes its parameters from its input through a learned parameter map, while a fixed call such as Normal(loc=0, scale=1) has constant parameters.

families

Parameterized distribution families as continuous morphisms.

Each family is a ContinuousMorphism whose codomain is a continuous space and whose conditional distribution p(y | x) belongs to a specific parametric family. The parameters are learnable functions of x:

  • For discrete domains (FinSet): parameters are looked up from a table.
  • For continuous domains (ContinuousSpace): parameters are produced by a small neural network.

This module wraps every reparameterizable distribution in torch.distributions as a conditional morphism, plus custom families (TruncatedNormal, MultivariateNormal, etc.).

Architecture

Most per-dimension-independent distributions are built on a shared generic base _IndependentConditional that handles the parameter source, transform, and torch.distributions plumbing. The _make_family class factory generates named classes from a specification. Distributions that need special handling (MultivariateNormal, Dirichlet, TruncatedNormal, etc.) are implemented as standalone classes.

ConditionalCauchy module-attribute

ConditionalCauchy = _make_family('ConditionalCauchy', D.Cauchy, [('loc', 'id'), ('scale', 'softplus')], 'Conditional Cauchy(loc(x), scale(x)). Heavy-tailed, no finite moments.')

Conditional Cauchy(loc(x), scale(x)). Heavy-tailed, no finite moments.

ConditionalLaplace module-attribute

ConditionalLaplace = _make_family('ConditionalLaplace', D.Laplace, [('loc', 'id'), ('scale', 'softplus')], 'Conditional Laplace(loc(x), scale(x)). Sharp peak, heavier tails than normal.')

Conditional Laplace(loc(x), scale(x)). Sharp peak, heavier tails than normal.

ConditionalCOMPoisson module-attribute

ConditionalCOMPoisson = _make_family('ConditionalCOMPoisson', COMPoisson, [('rate', 'softplus'), ('dispersion', 'softplus')], 'Conditional Conway--Maxwell--Poisson rate and dispersion.', discrete=True, inline_bounds={'rate': (0.0, math.inf)})

Conditional COM-Poisson count law.

ConditionalWiener module-attribute

ConditionalWiener = _make_family('ConditionalWiener', Wiener, [('boundary', 'softplus'), ('ndt', 'softplus'), ('bias', 'sigmoid'), ('drift', 'id')], 'Conditional joint signed Wiener reaction times and boundary decisions.', discrete=False, inline_bounds={'ndt': (0.0, math.inf)})

Conditional Wiener joint signed response-time law.

ConditionalDiscreteWeibull module-attribute

ConditionalDiscreteWeibull = _make_family('ConditionalDiscreteWeibull', DiscreteWeibull, [('probs', 'sigmoid'), ('concentration', 'softplus')], 'Conditional discrete Weibull survival probability and positive power.', discrete=True)

Conditional discrete Weibull count law.

ConditionalZeroInflatedAsymmetricLaplace module-attribute

ConditionalZeroInflatedAsymmetricLaplace = _make_family('ConditionalZeroInflatedAsymmetricLaplace', ZeroInflatedAsymmetricLaplace, [('zero_prob', 'sigmoid'), ('loc', 'id'), ('scale', 'softplus'), ('quantile', 'sigmoid')], 'Conditional structural zero and asymmetric Laplace quantile response.', discrete=False)

Conditional zero atom and asymmetric Laplace continuous component.

ConditionalAsymmetricLaplace module-attribute

ConditionalAsymmetricLaplace = _make_family('ConditionalAsymmetricLaplace', AsymmetricLaplace, [('loc', 'id'), ('scale', 'softplus'), ('quantile', 'sigmoid')], 'Conditional asymmetric Laplace with input-driven location, scale, and quantile.')

Conditional quantile regression distribution with three input-driven parameters.

ConditionalExGaussian module-attribute

ConditionalExGaussian = _make_family('ConditionalExGaussian', ExGaussian, [('loc', 'id'), ('scale', 'softplus'), ('rate', 'softplus')], 'Conditional exponentially modified Gaussian with location, Normal scale, and Exponential rate.')

Conditional sum of a Normal and an independent Exponential variable.

ConditionalExtendedBeta module-attribute

ConditionalExtendedBeta = _make_family('ConditionalExtendedBeta', ExtendedBeta, [('mu', 'sigmoid'), ('phi', 'softplus'), ('kappa', 'softplus')], 'Conditional censored extended Beta with mean, precision, and extension heads.', discrete=False, inline_bounds={'kappa': (0.0, math.inf)})

Conditional extended-Beta component parameters with endpoint censoring atoms.

ConditionalInverseGaussian module-attribute

ConditionalInverseGaussian = _make_family('ConditionalInverseGaussian', InverseGaussian, [('mu', 'softplus'), ('shape', 'softplus')], 'Conditional inverse Gaussian with input-driven mean and shape.')

Conditional inverse Gaussian with implicit reparameterized sampling.

ConditionalHurdleGamma module-attribute

ConditionalHurdleGamma = _make_family('ConditionalHurdleGamma', HurdleGamma, [('zero_prob', 'sigmoid'), ('concentration', 'softplus'), ('rate', 'softplus')], 'Conditional structural zero probability and Gamma shape/rate response.', discrete=False)

Conditional zero atom combined with a positive Gamma component.

ConditionalHurdleLogNormal module-attribute

ConditionalHurdleLogNormal = _make_family('ConditionalHurdleLogNormal', HurdleLogNormal, [('zero_prob', 'sigmoid'), ('loc', 'id'), ('scale', 'softplus')], 'Conditional structural zero probability and LogNormal log-location/log-scale response.', discrete=False)

Conditional zero atom combined with a positive LogNormal component.

ConditionalSkewNormal module-attribute

ConditionalSkewNormal = _make_family('ConditionalSkewNormal', SkewNormal, [('loc', 'id'), ('scale', 'softplus'), ('skewness', 'id')], 'Conditional SkewNormal response distribution.')

Conditional skew-normal with learned location, positive scale, and real skewness.

ConditionalShiftedLogNormal module-attribute

ConditionalShiftedLogNormal = _make_family('ConditionalShiftedLogNormal', ShiftedLogNormal, [('loc', 'id'), ('scale', 'softplus'), ('shift', 'softplus')], 'Conditional ShiftedLogNormal response distribution.', support=_constraints.real, inline_bounds={'shift': (0.0, math.inf)})

Conditional lognormal component with a learned nonnegative additive shift.

ConditionalFrechet module-attribute

ConditionalFrechet = _make_family('ConditionalFrechet', Frechet, [('scale', 'softplus'), ('concentration', 'softplus')], 'Conditional Frechet response distribution.')

Conditional Fréchet with learned positive scale and concentration.

ConditionalGeneralizedExtremeValue module-attribute

ConditionalGeneralizedExtremeValue = _make_family('ConditionalGeneralizedExtremeValue', GeneralizedExtremeValue, [('loc', 'id'), ('scale', 'softplus'), ('concentration', 'id')], 'Conditional GeneralizedExtremeValue response distribution.', support=_constraints.real)

Conditional generalized extreme value with learned location, scale, and tail index.

ConditionalGumbel module-attribute

ConditionalGumbel = _make_family('ConditionalGumbel', D.Gumbel, [('loc', 'id'), ('scale', 'softplus')], 'Conditional Gumbel(loc(x), scale(x)). Extreme value distribution (type I).')

Conditional Gumbel(loc(x), scale(x)). Extreme value distribution (type I).

ConditionalLogNormal module-attribute

ConditionalLogNormal = _make_family('ConditionalLogNormal', D.LogNormal, [('loc', 'id'), ('scale', 'softplus')], 'Conditional LogNormal(loc(x), scale(x)). Positive-valued, right-skewed.')

Conditional LogNormal(loc(x), scale(x)). Positive-valued, right-skewed.

ConditionalStudentT module-attribute

ConditionalStudentT = _make_family('ConditionalStudentT', D.StudentT, [('df', 'softplus_shifted'), ('loc', 'id'), ('scale', 'softplus')], 'Conditional StudentT(df(x), loc(x), scale(x)). Heavy-tailed with learnable df.')

Conditional StudentT(df(x), loc(x), scale(x)). Heavy-tailed with learnable df.

ConditionalExponential module-attribute

ConditionalExponential = _make_family('ConditionalExponential', D.Exponential, [('rate', 'softplus')], 'Conditional Exponential(rate(x)). Memoryless, positive-valued.')

Conditional Exponential(rate(x)). Memoryless, positive-valued.

ConditionalGamma module-attribute

ConditionalGamma = _make_family('ConditionalGamma', D.Gamma, [('concentration', 'softplus_shifted'), ('rate', 'softplus')], 'Conditional Gamma(concentration(x), rate(x)). Positive-valued, flexible shape.')

Conditional Gamma(concentration(x), rate(x)). Positive-valued, flexible shape.

ConditionalChi2 module-attribute

ConditionalChi2 = _make_family('ConditionalChi2', D.Chi2, [('df', 'softplus_shifted')], 'Conditional Chi2(df(x)). Positive-valued, sum of squared normals.')

Conditional Chi2(df(x)). Positive-valued, sum of squared normals.

ConditionalHalfCauchy module-attribute

ConditionalHalfCauchy = _make_family('ConditionalHalfCauchy', D.HalfCauchy, [('scale', 'softplus')], 'Conditional HalfCauchy(scale(x)). Heavy-tailed positive prior.')

Conditional HalfCauchy(scale(x)). Heavy-tailed positive prior.

ConditionalHalfNormal module-attribute

ConditionalHalfNormal = _make_family('ConditionalHalfNormal', D.HalfNormal, [('scale', 'softplus')], 'Conditional HalfNormal(scale(x)). Folded normal, positive-valued.')

Conditional HalfNormal(scale(x)). Folded normal, positive-valued.

ConditionalInverseGamma module-attribute

ConditionalInverseGamma = _make_family('ConditionalInverseGamma', D.InverseGamma, [('concentration', 'softplus_shifted'), ('rate', 'softplus')], 'Conditional InverseGamma(concentration(x), rate(x)). Conjugate prior for normal variance.')

Conditional InverseGamma(concentration(x), rate(x)). Conjugate prior for normal variance.

ConditionalWeibull module-attribute

ConditionalWeibull = _make_family('ConditionalWeibull', D.Weibull, [('scale', 'softplus'), ('concentration', 'softplus')], 'Conditional Weibull(scale(x), concentration(x)). Survival analysis, reliability.')

Conditional Weibull(scale(x), concentration(x)). Survival analysis, reliability.

ConditionalPareto module-attribute

ConditionalPareto = _make_family('ConditionalPareto', D.Pareto, [('scale', 'softplus'), ('alpha', 'softplus')], 'Conditional Pareto(scale(x), alpha(x)). Power-law tail.')

Conditional Pareto(scale(x), alpha(x)). Power-law tail.

ConditionalLogGamma module-attribute

ConditionalLogGamma = _make_family('ConditionalLogGamma', LogGamma, [('concentration', 'softplus'), ('rate', 'softplus')], 'Conditional LogGamma(concentration(x), rate(x)). The log of a Gamma variable, scored and sampled on the real line.')

Conditional LogGamma(concentration(x), rate(x)). The log of a Gamma variable, scored and sampled on the real line.

ConditionalLogitBeta module-attribute

ConditionalLogitBeta = _make_family('ConditionalLogitBeta', LogitBeta, [('concentration1', 'softplus'), ('concentration0', 'softplus')], 'Conditional LogitBeta(a(x), b(x)). The logit of a Beta variable, scored and sampled on the real line.')

Conditional LogitBeta(a(x), b(x)). The logit of a Beta variable, scored and sampled on the real line.

ConditionalKumaraswamy module-attribute

ConditionalKumaraswamy = _make_family('ConditionalKumaraswamy', D.Kumaraswamy, [('concentration1', 'softplus_shifted'), ('concentration0', 'softplus_shifted')], 'Conditional Kumaraswamy(a(x), b(x)). Beta-like on (0,1), closed-form CDF.')

Conditional Kumaraswamy(a(x), b(x)). Beta-like on (0,1), closed-form CDF.

ConditionalContinuousBernoulli module-attribute

ConditionalContinuousBernoulli = _make_family('ConditionalContinuousBernoulli', _LogSpaceContinuousBernoulli, [('logits', 'id')], 'Conditional ContinuousBernoulli(logits(x)). Continuous relaxation of Bernoulli.')

Conditional ContinuousBernoulli(logits(x)). Continuous relaxation of Bernoulli.

ConditionalFisherSnedecor module-attribute

ConditionalFisherSnedecor = _make_family('ConditionalFisherSnedecor', D.FisherSnedecor, [('df1', 'softplus_shifted'), ('df2', 'softplus_shifted')], 'Conditional FisherSnedecor(df1(x), df2(x)). F-distribution, ratio of chi-squared.')

Conditional FisherSnedecor(df1(x), df2(x)). F-distribution, ratio of chi-squared.

ConditionalPoisson module-attribute

ConditionalPoisson = _make_family('ConditionalPoisson', ClosedPoisson, [('rate', 'softplus')], 'Conditional Poisson(rate(x)). Discrete, non-negative integer counts.', inline_bounds={'rate': (0.0, math.inf)})

Conditional Poisson(rate(x)). Discrete, non-negative integer counts.

ConditionalZeroInflatedNegativeBinomial module-attribute

ConditionalZeroInflatedNegativeBinomial = _make_family('ConditionalZeroInflatedNegativeBinomial', ZeroInflatedNegativeBinomial, [('zero_prob', 'sigmoid'), ('total_count', 'softplus_shifted'), ('probs', 'sigmoid')], 'Conditional structural zeros plus a negative binomial count.', inline_bounds={'zero_prob': (0.0, 1.0), 'total_count': (0.0, math.inf), 'probs': (0.0, 1.0)})

Conditional zero-inflated negative binomial with three parameter heads.

ConditionalHurdleNegativeBinomial module-attribute

ConditionalHurdleNegativeBinomial = _make_family('ConditionalHurdleNegativeBinomial', HurdleNegativeBinomial, [('zero_prob', 'sigmoid'), ('total_count', 'softplus_shifted'), ('probs', 'sigmoid')], 'Conditional structural zeros plus a normalized positive negative binomial.', inline_bounds={'zero_prob': (0.0, 1.0), 'probs': (0.0, 1.0)})

Conditional hurdle negative binomial with an efficiently sampled positive count.

ConditionalGeometric module-attribute

ConditionalGeometric = _make_family('ConditionalGeometric', ClosedGeometric, [('probs', 'sigmoid')], 'Conditional Geometric(probs(x)). Number of failures before first success.', inline_bounds={'probs': (0.0, 1.0)})

Conditional Geometric(probs(x)). Number of failures before first success.

ConditionalNegativeBinomial module-attribute

ConditionalNegativeBinomial = _make_family('ConditionalNegativeBinomial', ClosedNegativeBinomial, [('total_count', 'softplus_shifted'), ('probs', 'sigmoid')], 'Conditional NegativeBinomial(total_count(x), probs(x)). Discrete, over-dispersed count distribution.', inline_bounds={'total_count': (0.0, math.inf), 'probs': (0.0, 1.0)})

Conditional NegativeBinomial(total_count(x), probs(x)). Discrete, over-dispersed count distribution.

ConditionalVonMises module-attribute

ConditionalVonMises = _make_family('ConditionalVonMises', D.VonMises, [('loc', 'id'), ('concentration', 'softplus')], 'Conditional VonMises(loc(x), concentration(x)). Circular analogue of the Normal distribution.', discrete=False)

Conditional VonMises(loc(x), concentration(x)). Circular analogue of the Normal distribution.

COMPoisson

COMPoisson(rate=None, dispersion=1.0, *, log_rate=None, validate_args=None, normalization_rtol=1e-12, max_terms=262144, max_proposals=10000)

Bases: Distribution

Counts proportional to rate**k / (k!)**dispersion.

PARAMETER DESCRIPTION
rate

Nonnegative rate. Supply exactly one of rate and log_rate.

TYPE: Tensor or float or None DEFAULT: None

dispersion

Strictly positive dispersion exponent.

TYPE: Tensor or float DEFAULT: 1.0

log_rate

Logarithm of the rate, permitting rates beyond floating-point range.

TYPE: Tensor or float or None DEFAULT: None

validate_args

Whether to validate parameters and samples.

TYPE: bool or None DEFAULT: None

normalization_rtol

Certified relative tail tolerance for normalization and moments.

TYPE: float DEFAULT: 1e-12

max_terms

Maximum centered count cells per row before an explicit refusal.

TYPE: int DEFAULT: 262144

max_proposals

Maximum rejection rounds per requested sample.

TYPE: int DEFAULT: 10000

Source code in src/quivers/continuous/_com_poisson.py
def __init__(
    self,
    rate=None,
    dispersion=1.0,
    *,
    log_rate=None,
    validate_args=None,
    normalization_rtol=1e-12,
    max_terms=262144,
    max_proposals=10000,
):
    if (rate is None) == (log_rate is None):
        raise ValueError("COMPoisson requires exactly one of rate and log_rate")
    if (
        not 0 < normalization_rtol < 1
        or not isinstance(max_terms, int)
        or not isinstance(max_proposals, int)
        or max_terms < 1
        or max_proposals < 1
    ):
        raise ValueError(
            "COMPoisson tolerances and resource budgets must be positive"
        )
    first, self.dispersion = _broadcast_count_parameters(
        log_rate if rate is None else rate, dispersion
    )
    if rate is None:
        self.log_rate = first
        self.rate = first.exp()
        self._boundary_rate = torch.zeros_like(first)
    else:
        self.rate = first
        self._boundary_rate = first
        demand(
            torch.isfinite(first) & (first >= 0),
            lambda: ValueError("COMPoisson rate must be finite and nonnegative"),
        )
        positive = first > 0
        self.log_rate = torch.where(
            positive, torch.where(positive, first, 1.0).log(), -torch.inf
        )
    demand(
        torch.isfinite(self.dispersion) & (self.dispersion > 0),
        lambda: ValueError("COMPoisson dispersion must be finite and positive"),
    )
    demand(
        torch.isfinite(self.log_rate) | (self.log_rate == -torch.inf),
        lambda: ValueError(
            "COMPoisson log_rate must be finite or negative infinity"
        ),
    )
    self.normalization_rtol = normalization_rtol
    self.max_terms = max_terms
    self.max_proposals = max_proposals
    # The negative-infinite log rate is the admitted zero-rate limit.
    super().__init__(self.dispersion.shape, validate_args=False)
    self._validate_args = bool(validate_args)

mean property

mean

Return a certified response mean.

RETURNS DESCRIPTION
Tensor

Float64 response means.

variance property

variance

Return a certified response variance.

RETURNS DESCRIPTION
Tensor

Float64 response variances.

expand

expand(batch_shape, _instance=None)

Expand parameter views while retaining the numerical policy.

PARAMETER DESCRIPTION
batch_shape

Requested batch shape.

TYPE: Size or Sequence[int]

_instance

Unused torch expansion hook.

TYPE: COMPoisson or None DEFAULT: None

RETURNS DESCRIPTION
COMPoisson

Expanded distribution.

Source code in src/quivers/continuous/_com_poisson.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views while retaining the numerical policy.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested batch shape.
    _instance : COMPoisson or None
        Unused torch expansion hook.

    Returns
    -------
    COMPoisson
        Expanded distribution.
    """
    result = COMPoisson(
        log_rate=self.log_rate.expand(batch_shape),
        dispersion=self.dispersion.expand(batch_shape),
        validate_args=self._validate_args,
        normalization_rtol=self.normalization_rtol,
        max_terms=self.max_terms,
        max_proposals=self.max_proposals,
    )
    result._boundary_rate = self._boundary_rate.expand(batch_shape)
    return result

log_prob

log_prob(value)

Score counts with a certified centered normalizer.

PARAMETER DESCRIPTION
value

Candidate count values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Float64 log masses, negative infinity off support.

Source code in src/quivers/continuous/_com_poisson.py
def log_prob(self, value):
    """Score counts with a certified centered normalizer.

    Parameters
    ----------
    value : Tensor
        Candidate count values.

    Returns
    -------
    Tensor
        Float64 log masses, negative infinity off support.
    """
    _check_count_observation_source(value)
    value = torch.as_tensor(
        value, device=self.dispersion.device, dtype=torch.float64
    )
    if self._validate_args:
        self._validate_sample(value)
    mode, log_sum, _, _ = self._statistics()
    log_rate, nu, _ = self._parameters()
    valid = torch.isfinite(value) & (value >= 0) & (value == value.floor())
    result = (
        _relative_weight(torch.where(valid, value, 0.0), log_rate, nu, mode)
        - log_sum
    )
    result = torch.where(
        self.log_rate == -torch.inf,
        torch.where(value == 0, -self._boundary_rate, -torch.inf),
        result,
    )
    return torch.where(valid, result, -torch.inf)

sample

sample(sample_shape=Size())

Sample from a log-concave envelope without truncating the law.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 count samples.

RAISES DESCRIPTION
RuntimeError

If a proposal exceeds exact count capacity or the round budget.

Source code in src/quivers/continuous/_com_poisson.py
def sample(self, sample_shape=torch.Size()):
    """Sample from a log-concave envelope without truncating the law.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Int64 count samples.

    Raises
    ------
    RuntimeError
        If a proposal exceeds exact count capacity or the round budget.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        log_rate = self.log_rate.expand(shape).reshape(-1)
        nu = self.dispersion.expand(shape).reshape(-1)
        output = torch.zeros_like(log_rate)
        active = torch.nonzero(torch.isfinite(log_rate), as_tuple=True)[0]
        for _ in range(self.max_proposals):
            if active.numel() == 0:
                return output.reshape(shape).to(torch.int64)
            lr, power = log_rate[active], nu[active]
            rho = _require_sample_capacity((lr / power).exp())
            mode = rho.floor()
            width = (rho / power).sqrt().clamp_min(1)
            left = (mode - width.ceil()).clamp_min(0)
            right = _require_sample_capacity(mode + width.ceil())
            log_lratio = power * left.clamp_min(1).log() - lr
            log_rratio = lr - power * (right + 1).log()
            lweight = _relative_weight(left, lr, power, mode)
            rweight = _relative_weight(right, lr, power, mode)
            lmass = torch.where(
                left > 0,
                (lweight + log_lratio).exp() / -torch.expm1(log_lratio),
                0.0,
            )
            rmass = (rweight + log_rratio).exp() / -torch.expm1(log_rratio)
            middle = right - left + 1
            pick = torch.rand_like(lr) * (middle + lmass + rmass)
            in_left = pick < lmass
            in_right = pick >= lmass + middle
            u = torch.rand_like(lr).clamp_min(torch.finfo(torch.float64).tiny)
            safe_lratio = torch.where(left > 0, log_lratio, -1.0)
            lj = (u.log() / safe_lratio).floor() + 1
            rj = (u.log() / log_rratio).floor() + 1
            center = left + (torch.rand_like(lr) * middle).floor()
            candidate = torch.where(
                in_left, left - lj, torch.where(in_right, right + rj, center)
            )
            nonnegative = candidate >= 0
            _require_sample_capacity(candidate.clamp_min(0))
            envelope = torch.where(
                in_left,
                lweight + lj * log_lratio,
                torch.where(in_right, rweight + rj * log_rratio, 0.0),
            )
            actual = _relative_weight(candidate.clamp_min(0), lr, power, mode)
            accept = nonnegative & (torch.rand_like(lr).log() <= actual - envelope)
            output[active[accept]] = candidate[accept]
            active = active[~accept]
    raise RuntimeError("COMPoisson rejection sampling exhausted max_proposals")

BernsteinHazard

BernsteinHazard(breaks, controls, rate=None, *, log_rate=None, validate_args=None)

Bases: Distribution

A normalized positive baseline hazard and a proportional rate.

PARAMETER DESCRIPTION
breaks

Strictly increasing finite boundaries with trailing shape (S+1,), starting at zero.

TYPE: Tensor or Sequence[float]

controls

Positive Bernstein coefficients of trailing shape (S,K). The integrated baseline over the finite interval must equal one.

TYPE: Tensor or Sequence[Sequence[float]]

rate

Positive hazard multiplier, exclusive with log_rate.

TYPE: Tensor or float DEFAULT: None

log_rate

Finite log hazard multiplier.

TYPE: Tensor or float DEFAULT: None

validate_args

Torch parameter-validation policy.

TYPE: bool or None DEFAULT: None

Notes

The final hazard value continues constantly beyond the upper boundary. This positive tail retains total probability one. Normalizing the finite baseline integral identifies its shape separately from the rate. The immutable finite_moment_orders certificate records the first two finite moments; an analytic formula for those moments is not provided.

Source code in src/quivers/continuous/_bernstein_hazard.py
def __init__(
    self, breaks, controls, rate=None, *, log_rate=None, validate_args=None
):
    if (rate is None) == (log_rate is None):
        raise ValueError("supply exactly one of rate and log_rate")
    device = next(
        (
            value.device
            for value in (controls, breaks, rate, log_rate)
            if isinstance(value, Tensor)
        ),
        None,
    )
    if isinstance(rate, bool) or isinstance(log_rate, bool):
        raise ValueError("Bernstein hazard rate must be real, not Boolean")
    raw_breaks = (
        torch.as_tensor(breaks, device=device)
        if isinstance(breaks, Tensor)
        else torch.as_tensor(breaks, dtype=torch.float64, device=device)
    )
    raw_controls = (
        torch.as_tensor(controls, device=device)
        if isinstance(controls, Tensor)
        else torch.as_tensor(controls, dtype=torch.float64, device=device)
    )
    if raw_breaks.dtype == torch.bool or raw_controls.dtype == torch.bool:
        raise ValueError(
            "Bernstein structural parameters must be real, not Boolean"
        )
    self.breaks = raw_breaks.to(torch.float64)
    self.controls = raw_controls.to(torch.float64)
    if self.breaks.ndim < 1 or self.controls.ndim < 2:
        raise ValueError(
            "Bernstein hazard needs a boundary vector and coefficient matrix"
        )
    segments, width = self.controls.shape[-2:]
    if segments < 1 or width < 1 or self.breaks.shape[-1] != segments + 1:
        raise ValueError(
            "Bernstein boundaries[S+1] must match controls[S,K] with S,K positive"
        )
    value = rate if rate is not None else log_rate
    raw = (
        torch.as_tensor(value, device=device)
        if isinstance(value, Tensor)
        else torch.as_tensor(value, dtype=torch.float64, device=device)
    )
    if raw.dtype == torch.bool:
        raise ValueError("Bernstein hazard rate must be real, not Boolean")
    raw = raw.to(torch.float64)
    if rate is not None:
        if validate_args is not False:
            demand(
                torch.isfinite(raw) & (raw > 0),
                lambda: ValueError(
                    "Bernstein hazard rate must be finite and positive"
                ),
            )
        raw = raw.log()
    batch = torch.broadcast_shapes(
        self.breaks.shape[:-1], self.controls.shape[:-2], raw.shape
    )
    self.breaks = self.breaks.expand(*batch, segments + 1)
    self.controls = self.controls.expand(*batch, segments, width)
    self.log_rate = raw.expand(batch)
    intervals = self.breaks[..., 1:] - self.breaks[..., :-1]
    area = intervals * (self.controls / width).sum(-1)
    if validate_args is not False:
        demand(
            torch.isfinite(self.breaks).all(-1)
            & (self.breaks[..., 0] == 0)
            & ((intervals > 0) & torch.isfinite(intervals)).all(-1),
            lambda: ValueError(
                "Bernstein boundaries must start zero and increase finitely"
            ),
        )
        demand(
            torch.isfinite(self.controls) & (self.controls > 0),
            lambda: ValueError(
                "Bernstein controls must be finite and strictly positive"
            ),
        )
        demand(
            torch.isfinite(self.log_rate),
            lambda: ValueError("Bernstein log rate must be finite"),
        )
        demand(
            torch.isclose(area.sum(-1), area.new_tensor(1.0), rtol=1e-6, atol=1e-8),
            lambda: ValueError("Bernstein baseline integral must equal one"),
        )
    local = (self.controls / width) * intervals[..., None]
    prefix = torch.cat(
        (torch.zeros_like(area[..., :1]), area.cumsum(-1)[..., :-1]), -1
    )
    self._integrals = prefix[..., None] + torch.cat(
        (torch.zeros_like(local[..., :1]), local.cumsum(-1)), -1
    )
    super().__init__(batch, validate_args=validate_args)

rate property

rate

Return the proportional multiplier when representable.

RETURNS DESCRIPTION
Tensor

Exponentiated log rate. Density and tail calculations retain log-rate arithmetic even when this view overflows.

expand

expand(batch_shape, _instance=None)

Expand parameter views without rebuilding the integrated table.

PARAMETER DESCRIPTION
batch_shape

Requested leading batch dimensions.

TYPE: Size

_instance

Optional instance populated through the Torch expansion protocol.

TYPE: BernsteinHazard or None DEFAULT: None

RETURNS DESCRIPTION
BernsteinHazard

Distribution retaining the same baseline and integrated table.

Source code in src/quivers/continuous/_bernstein_hazard.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without rebuilding the integrated table.

    Parameters
    ----------
    batch_shape : torch.Size
        Requested leading batch dimensions.
    _instance : BernsteinHazard or None
        Optional instance populated through the Torch expansion protocol.

    Returns
    -------
    BernsteinHazard
        Distribution retaining the same baseline and integrated table.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    new.breaks = self.breaks.expand(*shape, self.breaks.shape[-1])
    new.controls = self.controls.expand(*shape, *self.controls.shape[-2:])
    new.log_rate = self.log_rate.expand(shape)
    new._integrals = self._integrals.expand(*shape, *self._integrals.shape[-2:])
    super(BernsteinHazard, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate the normalized time density on the nonnegative support.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Normalized log density, negative infinity outside the support.

RAISES DESCRIPTION
ValueError

If the time is NaN.

Source code in src/quivers/continuous/_bernstein_hazard.py
def log_prob(self, value):
    """Evaluate the normalized time density on the nonnegative support.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Normalized log density, negative infinity outside the support.

    Raises
    ------
    ValueError
        If the time is NaN.
    """
    value = self._value(value)
    safe = torch.where(
        torch.isfinite(value) & (value >= 0),
        value,
        self.breaks[..., -1],
    )
    hazard, _ = self._baseline(
        torch.where(safe > self.breaks[..., -1], self.breaks[..., -1], safe)
    )
    cumulative = self._cumulative(value)
    result = self.log_rate + hazard.log() - cumulative
    return torch.where(torch.isfinite(value) & (value >= 0), result, -torch.inf)

log_survival_function

log_survival_function(value)

Evaluate log survival directly from the integrated hazard.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Log survival, evaluated directly from cumulative hazard.

Source code in src/quivers/continuous/_bernstein_hazard.py
def log_survival_function(self, value):
    """Evaluate log survival directly from the integrated hazard.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Log survival, evaluated directly from cumulative hazard.
    """
    value = self._value(value)
    return -self._cumulative(value)

cdf

cdf(value)

Evaluate cumulative event probability, including exact support tails.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Cumulative event probability.

Source code in src/quivers/continuous/_bernstein_hazard.py
def cdf(self, value):
    """Evaluate cumulative event probability, including exact support tails.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Cumulative event probability.
    """
    return -torch.expm1(self.log_survival_function(value))

log_cdf

log_cdf(value)

Evaluate log CDF without subtracting small survival probabilities.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Log cumulative probability, retaining small positive probabilities.

Source code in src/quivers/continuous/_bernstein_hazard.py
def log_cdf(self, value):
    """Evaluate log CDF without subtracting small survival probabilities.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Log cumulative probability, retaining small positive probabilities.
    """
    value = self._value(value)
    return _log1mexp_neg_exp(self._log_cumulative(value))

icdf

icdf(value)

Invert the integrated hazard with a bounded, checked root solve.

PARAMETER DESCRIPTION
value

Probability in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Event quantile; the endpoints return zero and positive infinity.

RAISES DESCRIPTION
ValueError

If a probability is NaN or outside the unit interval.

FloatingPointError

If the finite positive quantile is unrepresentable.

RuntimeError

If the bounded root solver does not converge.

Source code in src/quivers/continuous/_bernstein_hazard.py
def icdf(self, value):
    """Invert the integrated hazard with a bounded, checked root solve.

    Parameters
    ----------
    value : Tensor
        Probability in the closed unit interval.

    Returns
    -------
    Tensor
        Event quantile; the endpoints return zero and positive infinity.

    Raises
    ------
    ValueError
        If a probability is NaN or outside the unit interval.
    FloatingPointError
        If the finite positive quantile is unrepresentable.
    RuntimeError
        If the bounded root solver does not converge.
    """
    value = torch.as_tensor(
        value, dtype=self.controls.dtype, device=self.controls.device
    )
    demand(
        ~((value < 0) | (value > 1) | torch.isnan(value)),
        lambda: ValueError(
            "Bernstein hazard quantile probability must lie in [0, 1]"
        ),
    )
    interior = (value > 0) & (value < 1)
    safe = torch.where(interior, value, value.new_tensor(0.5))
    log_target = (-torch.log1p(-safe)).log() - self.log_rate
    log_target = torch.where(
        interior, log_target, torch.full_like(log_target, -0.6931471805599453)
    )
    result = self._inverse_baseline(log_target)
    return torch.where(value == 0, 0.0, torch.where(value == 1, torch.inf, result))

rsample

rsample(sample_shape=Size())

Draw vectorized event times by inverse cumulative hazard.

PARAMETER DESCRIPTION
sample_shape

Independent sample dimensions preceding batch dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Pathwise event times from the full normalized law.

Source code in src/quivers/continuous/_bernstein_hazard.py
def rsample(self, sample_shape=torch.Size()):
    """Draw vectorized event times by inverse cumulative hazard.

    Parameters
    ----------
    sample_shape : torch.Size
        Independent sample dimensions preceding batch dimensions.

    Returns
    -------
    Tensor
        Pathwise event times from the full normalized law.
    """
    shape = self._extended_shape(sample_shape)
    exponential = torch.empty(
        shape, dtype=self.controls.dtype, device=self.controls.device
    ).exponential_()
    return self._inverse_baseline(exponential.log() - self.log_rate)

ExtendedBeta

ExtendedBeta(mu, phi, kappa, *, moment_atol=1e-12, moment_rtol=1e-10, moment_max_panels=4096, validate_args=None)

Bases: Censored

Extend a mean/precision Beta law and censor its tails at zero and one.

PARAMETER DESCRIPTION
mu

Underlying Beta mean, strictly between zero and one.

TYPE: Tensor or float

phi

Strictly positive Beta precision.

TYPE: Tensor or float

kappa

Nonnegative extension: Y=clamp((1+2*kappa)*X-kappa,0,1).

TYPE: Tensor or float

moment_atol

Deterministic bounded-moment quadrature error budgets.

TYPE: float DEFAULT: 1e-12

moment_rtol

Deterministic bounded-moment quadrature error budgets.

TYPE: float DEFAULT: 1e-12

moment_max_panels

Per-row adaptive panel limit; work is chunked over at most64 rows.

TYPE: int DEFAULT: 4096

validate_args

Torch validation policy; parameter validity is always checked.

TYPE: bool or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If parameters or numerical budgets are invalid.

RuntimeError

If the symmetric extension cannot retain its censoring bounds in Float64.

Source code in src/quivers/continuous/_extended_beta.py
def __init__(
    self,
    mu,
    phi,
    kappa,
    *,
    moment_atol=1e-12,
    moment_rtol=1e-10,
    moment_max_panels=4096,
    validate_args=None,
):
    device = next(
        (x.device for x in (mu, phi, kappa) if isinstance(x, Tensor)), None
    )
    self.mu, self.phi, self.kappa = torch.broadcast_tensors(
        *(
            torch.as_tensor(x, dtype=torch.float64, device=device)
            for x in (mu, phi, kappa)
        )
    )
    valid = (
        (self.mu > 0)
        & (self.mu < 1)
        & (self.phi > 0)
        & (self.kappa >= 0)
        & torch.isfinite(self.mu + self.phi + self.kappa)
    )
    demand(
        valid,
        lambda: ValueError(
            "ExtendedBeta requires mu in(0,1), finite phi>0 and kappa>=0"
        ),
    )
    if (
        not isinstance(moment_max_panels, int)
        or isinstance(moment_max_panels, bool)
        or moment_max_panels < 1
        or not math.isfinite(moment_atol)
        or not math.isfinite(moment_rtol)
        or moment_atol <= 0
        or moment_rtol <= 0
    ):
        raise ValueError("ExtendedBeta moment budgets must be finite and positive")
    self.moment_atol, self.moment_rtol = moment_atol, moment_rtol
    self.moment_max_panels = moment_max_panels
    width = 1 + 2 * self.kappa
    demand(
        torch.isfinite(width),
        lambda: RuntimeError(
            "ExtendedBeta extension exceeds Float64 affine capacity"
        ),
    )
    low = self.kappa / width
    high = 0.5 + 0.5 / width
    demand(
        (low < 0.5) & (high > 0.5),
        lambda: RuntimeError(
            "ExtendedBeta censoring bounds exceed Float64 interval resolution"
        ),
    )
    beta = _AffineBeta(
        self.mu * self.phi, (1 - self.mu) * self.phi, self.kappa, self.kappa
    )
    super().__init__(beta, 0.0, 1.0)
    self._validate_args = bool(validate_args)

mean property

mean: Tensor

True censored response mean, computed with deterministic error bounds.

RETURNS DESCRIPTION
Tensor

Mean on the parameter batch axes, generally different from mu.

variance property

variance: Tensor

Positive within/between response variance without raw-moment cancellation.

RETURNS DESCRIPTION
Tensor

Variance on the parameter batch axes.

expand

expand(batch_shape, _instance=None)

Broadcast the same law and deterministic moment budgets.

PARAMETER DESCRIPTION
batch_shape

Requested parameter batch shape.

TYPE: Size or Sequence[int]

_instance

Optional Torch expansion instance.

TYPE: ExtendedBeta or None DEFAULT: None

RETURNS DESCRIPTION
ExtendedBeta

Expanded distribution, retaining the same numerical policy.

Source code in src/quivers/continuous/_extended_beta.py
def expand(self, batch_shape, _instance=None):
    """Broadcast the same law and deterministic moment budgets.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested parameter batch shape.
    _instance : ExtendedBeta or None
        Optional Torch expansion instance.

    Returns
    -------
    ExtendedBeta
        Expanded distribution, retaining the same numerical policy.
    """
    return type(self)(
        self.mu.expand(batch_shape),
        self.phi.expand(batch_shape),
        self.kappa.expand(batch_shape),
        moment_atol=self.moment_atol,
        moment_rtol=self.moment_rtol,
        moment_max_panels=self.moment_max_panels,
        validate_args=self._validate_args,
    )

sample

sample(sample_shape: Size | tuple[int, ...] | list[int] = Size())

Draw censoring atoms before rounding complementary Beta weights.

PARAMETER DESCRIPTION
sample_shape

Leading independent sample axes.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Distribution result on the requested sample and batch axes.

RAISES DESCRIPTION
RuntimeError

If the evaluation or sample exceeds the documented numerical capacity.

Source code in src/quivers/continuous/_extended_beta.py
def sample(
    self, sample_shape: torch.Size | tuple[int, ...] | list[int] = torch.Size()
):
    """Draw censoring atoms before rounding complementary Beta weights.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading independent sample axes.

    Returns
    -------
    Tensor
        Distribution result on the requested sample and batch axes.

    Raises
    ------
    RuntimeError
        If the evaluation or sample exceeds the documented numerical capacity.
    """
    with torch.no_grad():
        return cast(_AffineBeta, self.base)._sample_unit_censored(
            sample_shape, reparameterized=False
        )

rsample

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

Draw pathwise responses, refusing unrepresentable interior samples.

PARAMETER DESCRIPTION
sample_shape

Leading independent sample axes.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Distribution result on the requested sample and batch axes.

Source code in src/quivers/continuous/_extended_beta.py
def rsample(
    self, sample_shape: torch.Size | tuple[int, ...] | list[int] = torch.Size()
):
    """Draw pathwise responses, refusing unrepresentable interior samples.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading independent sample axes.

    Returns
    -------
    Tensor
        Distribution result on the requested sample and batch axes.
    """
    return cast(_AffineBeta, self.base)._sample_unit_censored(
        sample_shape, reparameterized=True
    )

CoxPH

CoxPH(basis, weights, rate=None, *, log_rate=None, validate_args=None)

Bases: BernsteinHazard

Proportional hazards with a retained normalized M-spline basis.

PARAMETER DESCRIPTION
basis

Immutable fitted knots, degree, and constant endpoint tail.

TYPE: MSplineBasis

weights

Strictly positive simplex weights over basis components.

TYPE: Tensor or Sequence[float]

rate

Positive proportional multiplier, exclusive with log_rate.

TYPE: Tensor or float DEFAULT: None

log_rate

Finite log multiplier.

TYPE: Tensor or float DEFAULT: None

validate_args

Torch parameter-validation policy.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_cox.py
def __init__(self, basis, weights, rate=None, *, log_rate=None, validate_args=None):
    if basis.boundary_knots[0] != 0:
        raise ValueError("Cox baseline must start at time zero")
    self.basis = basis
    device = next(
        (v.device for v in (weights, rate, log_rate) if isinstance(v, Tensor)), None
    )
    weights = torch.as_tensor(weights, dtype=torch.float64, device=device)
    if weights.ndim < 1 or weights.shape[-1] != basis.size:
        raise ValueError(f"Cox weights need {basis.size} spline components")
    if validate_args is not False:
        demand(
            (torch.isfinite(weights) & (weights > 0)).all(-1)
            & torch.isclose(
                weights.sum(-1), weights.new_tensor(1.0), rtol=1e-6, atol=1e-8
            ),
            lambda: ValueError(
                "Cox spline weights must be a strictly positive simplex"
            ),
        )
    self.weights = weights
    controls = torch.einsum(
        "...j,ijk->...ik", weights, weights.new_tensor(basis.m_coefficients)
    )
    super().__init__(
        weights.new_tensor(basis.breaks),
        controls,
        rate,
        log_rate=log_rate,
        validate_args=validate_args,
    )
    self.weights = weights.expand(*self.batch_shape, basis.size)

expand

expand(batch_shape, _instance=None)

Expand distribution views while retaining the original fitted basis.

PARAMETER DESCRIPTION
batch_shape

Requested leading batch dimensions.

TYPE: Size

_instance

Optional instance populated by the Torch expansion protocol.

TYPE: CoxPH or None DEFAULT: None

RETURNS DESCRIPTION
CoxPH

Expanded view retaining the fitted basis and weights.

Source code in src/quivers/continuous/_cox.py
def expand(self, batch_shape, _instance=None):
    """Expand distribution views while retaining the original fitted basis.

    Parameters
    ----------
    batch_shape : torch.Size
        Requested leading batch dimensions.
    _instance : CoxPH or None
        Optional instance populated by the Torch expansion protocol.

    Returns
    -------
    CoxPH
        Expanded view retaining the fitted basis and weights.
    """
    new = super().expand(batch_shape, _instance)
    new.basis = self.basis
    new.weights = self.weights.expand(*batch_shape, self.basis.size)
    return new

MSplineBasis dataclass

MSplineBasis(boundary_knots: tuple[float, float] = (0.0, 1.0), interior_knots: tuple[float, ...] = (), degree: int = 3, tail: str = 'constant')

Normalized M-splines, integrated I-splines, and a constant hazard tail.

PARAMETER DESCRIPTION
boundary_knots

Finite increasing endpoints of the fitted spline interval.

TYPE: tuple[float, float] DEFAULT: (0.0, 1.0)

interior_knots

Strictly increasing knots inside the boundary interval.

TYPE: tuple[float, ...] DEFAULT: ()

degree

Nonnegative polynomial degree of the M-splines.

TYPE: int DEFAULT: 3

tail

Hazard continuation; currently "constant" retains each M-spline's value at the upper boundary and integrates it linearly thereafter.

TYPE: str DEFAULT: 'constant'

Notes

Every M-spline integrates to one over the fitted interval. Below its lower boundary both bases are zero. The retained knots and tail policy are part of value equality, so prediction cannot silently rebuild a training basis.

size property

size: int

Return the number of retained spline components.

RETURNS DESCRIPTION
int

Number of retained normalized spline components.

__post_init__

__post_init__()

Validate immutable knots and construct normalized basis tables.

RAISES DESCRIPTION
ValueError

If knots, degree, tail policy, or basis normalization are invalid.

NotImplementedError

If the retained table exceeds the explicit coefficient budget.

Source code in src/quivers/_splines.py
def __post_init__(self):
    """Validate immutable knots and construct normalized basis tables.

    Raises
    ------
    ValueError
        If knots, degree, tail policy, or basis normalization are invalid.
    NotImplementedError
        If the retained table exceeds the explicit coefficient budget.
    """
    if (
        isinstance(self.degree, bool)
        or not isinstance(self.degree, int)
        or self.degree < 0
    ):
        raise ValueError("M-spline degree must be a nonnegative integer")
    if self.tail != "constant":
        raise ValueError("M-spline tail must be 'constant'")
    raw = (*self.boundary_knots, *self.interior_knots)
    if any(
        isinstance(v, bool) or not isinstance(v, Real) or not math.isfinite(v)
        for v in raw
    ):
        raise ValueError("spline knots must be finite real numbers")
    if len(self.boundary_knots) != 2:
        raise ValueError("exactly two boundary knots are required")
    lower, upper = map(float, self.boundary_knots)
    interior = tuple(map(float, self.interior_knots))
    breaks = (lower, *interior, upper)
    if any(a >= b for a, b in zip(breaks, breaks[1:])):
        raise ValueError(
            "spline knots must increase strictly within their boundaries"
        )
    if not math.isfinite(upper - lower):
        raise ValueError("spline interval width must be finite")
    object.__setattr__(self, "boundary_knots", (lower, upper))
    object.__setattr__(self, "interior_knots", interior)
    object.__setattr__(self, "breaks", breaks)
    p = self.degree
    size = len(interior) + p + 1
    if (len(interior) + 1) * size * (2 * p + 3) > 1_048_576:
        raise NotImplementedError(
            "retained spline table exceeds 1,048,576 coefficients"
        )
    knots = (lower,) * (p + 1) + interior + (upper,) * (p + 1)
    integrated = [0.0] * size
    m_pieces, i_pieces = [], []
    for a, b in zip(breaks, breaks[1:]):
        pieces = [
            [float(t <= a and b <= s and t < s)] for t, s in zip(knots, knots[1:])
        ]
        for degree in range(1, p + 1):
            following = []
            for i in range(len(pieces) - 1):
                left_width = knots[i + degree] - knots[i]
                right_width = knots[i + degree + 1] - knots[i + 1]
                left = (
                    _linear_product(
                        pieces[i],
                        (a - knots[i]) / left_width,
                        (b - knots[i]) / left_width,
                    )
                    if left_width
                    else [0.0] * (degree + 1)
                )
                right = (
                    _linear_product(
                        pieces[i + 1],
                        (knots[i + degree + 1] - a) / right_width,
                        (knots[i + degree + 1] - b) / right_width,
                    )
                    if right_width
                    else [0.0] * (degree + 1)
                )
                following.append([x + y for x, y in zip(left, right)])
            pieces = following
        m_piece, i_piece = [], []
        for i, polynomial in enumerate(pieces):
            scale = (p + 1) / (knots[i + p + 1] - knots[i])
            coefficients = tuple(scale * value for value in polynomial)
            integral = [integrated[i]]
            for value in coefficients:
                integral.append(integral[-1] + (b - a) * value / (p + 1))
            integrated[i] = integral[-1]
            m_piece.append(coefficients)
            i_piece.append(tuple(integral))
        m_pieces.append(tuple(m_piece))
        i_pieces.append(tuple(i_piece))
    if any(
        not math.isclose(value, 1.0, rel_tol=2e-12, abs_tol=2e-12)
        for value in integrated
    ):
        raise ValueError("spline basis cannot be normalized at these knots")
    object.__setattr__(self, "m_coefficients", tuple(m_pieces))
    object.__setattr__(self, "i_coefficients", tuple(i_pieces))

evaluate

evaluate(value: float) -> tuple[tuple[float, ...], tuple[float, ...]]

Evaluate the hazard basis and its integral, including the tail.

PARAMETER DESCRIPTION
value

Evaluation time, including support endpoints and infinities.

TYPE: float

RETURNS DESCRIPTION
tuple[tuple[float, ...], tuple[float, ...]]

M-spline values and integrated I-spline values in component order.

RAISES DESCRIPTION
ValueError

If the time is NaN.

Source code in src/quivers/_splines.py
def evaluate(self, value: float) -> tuple[tuple[float, ...], tuple[float, ...]]:
    """Evaluate the hazard basis and its integral, including the tail.

    Parameters
    ----------
    value : float
        Evaluation time, including support endpoints and infinities.

    Returns
    -------
    tuple[tuple[float, ...], tuple[float, ...]]
        M-spline values and integrated I-spline values in component order.

    Raises
    ------
    ValueError
        If the time is NaN.
    """
    if math.isnan(value):
        raise ValueError("spline argument must not be NaN")
    lower, upper = self.boundary_knots
    if value < lower:
        return (0.0,) * self.size, (0.0,) * self.size
    if value >= upper:
        m = tuple(piece[-1] for piece in self.m_coefficients[-1])
        i = tuple(piece[-1] for piece in self.i_coefficients[-1])
        if value > upper:
            i = tuple(y + x * (value - upper) if x else y for x, y in zip(m, i))
        return m, i
    import bisect

    index = bisect.bisect_right(self.breaks, value) - 1
    u = (value - self.breaks[index]) / (self.breaks[index + 1] - self.breaks[index])
    return (
        tuple(_bernstein_value(piece, u) for piece in self.m_coefficients[index]),
        tuple(_bernstein_value(piece, u) for piece in self.i_coefficients[index]),
    )

AdditiveLogRatioNormal

AdditiveLogRatioNormal(loc, scale_tril, reference=None, validate_args=None)

Bases: Distribution

A Gaussian law for log ratios against a selected simplex component.

PARAMETER DESCRIPTION
loc

Gaussian location with trailing width D.

TYPE: Tensor or Sequence[float]

scale_tril

Lower-triangular Gaussian scale with trailing shape (D, D).

TYPE: Tensor or Sequence[Sequence[float]]

reference

Reference component, broadcast over Gaussian batch dimensions. None selects the final component. Free coordinates retain the relative order of every other component.

TYPE: int or Tensor or None DEFAULT: None

validate_args

Torch distribution validation policy.

TYPE: bool or None DEFAULT: None

Notes

A draw has D + 1 components. The nonreference components retain their original order; their log ratios against the reference have the joint Gaussian law. The final component is the default reference. Analytic response means and variances are unavailable.

Source code in src/quivers/continuous/_additive_log_ratio.py
def __init__(self, loc, scale_tril, reference=None, validate_args=None):
    device = (
        loc.device
        if isinstance(loc, Tensor)
        else scale_tril.device
        if isinstance(scale_tril, Tensor)
        else None
    )
    loc = torch.as_tensor(loc, device=device)
    scale_tril = torch.as_tensor(scale_tril, device=device)
    dtype = torch.promote_types(loc.dtype, scale_tril.dtype)
    if not dtype.is_floating_point:
        dtype = torch.get_default_dtype()
    self._normal = MultivariateNormal(
        loc.to(dtype), scale_tril=scale_tril.to(dtype), validate_args=validate_args
    )
    width = self._normal.event_shape[0]
    selected = torch.as_tensor(
        width if reference is None else reference, device=device
    )
    if selected.dtype == torch.bool:
        raise ValueError(
            "AdditiveLogRatioNormal reference must be an integer component index"
        )
    demand(
        torch.isfinite(selected)
        & (selected >= 0)
        & (selected <= width)
        & (selected == selected.floor()),
        lambda: ValueError(
            "AdditiveLogRatioNormal reference must be an integer component index"
        ),
    )
    batch = torch.broadcast_shapes(self._normal.batch_shape, selected.shape)
    self._normal = self._normal.expand(batch)
    self.reference = selected.to(torch.long).expand(batch)
    self.loc = self._normal.loc
    self.scale_tril = self._normal.scale_tril
    if self.loc.shape[-1] < 1:
        raise ValueError(
            "AdditiveLogRatioNormal requires at least two simplex components"
        )
    super().__init__(
        self._normal.batch_shape,
        torch.Size((self.loc.shape[-1] + 1,)),
        validate_args=validate_args,
    )

expand

expand(batch_shape, _instance=None)

Broadcast the batch dimensions while retaining the coordinate event.

PARAMETER DESCRIPTION
batch_shape

New broadcast-compatible batch shape.

TYPE: Size

_instance

Optional instance populated by Torch's expansion protocol.

TYPE: AdditiveLogRatioNormal or None DEFAULT: None

RETURNS DESCRIPTION
AdditiveLogRatioNormal

Distribution with the requested batch shape.

Source code in src/quivers/continuous/_additive_log_ratio.py
def expand(self, batch_shape, _instance=None):
    """Broadcast the batch dimensions while retaining the coordinate event.

    Parameters
    ----------
    batch_shape : torch.Size
        New broadcast-compatible batch shape.
    _instance : AdditiveLogRatioNormal or None
        Optional instance populated by Torch's expansion protocol.

    Returns
    -------
    AdditiveLogRatioNormal
        Distribution with the requested batch shape.
    """
    new = self._get_checked_instance(AdditiveLogRatioNormal, _instance)
    new._normal = self._normal.expand(batch_shape)
    new.reference = self.reference.expand(batch_shape)
    new.loc = new._normal.loc
    new.scale_tril = new._normal.scale_tril
    super(AdditiveLogRatioNormal, new).__init__(
        torch.Size(batch_shape), self.event_shape, validate_args=False
    )
    new._validate_args = self._validate_args
    return new

rsample

rsample(sample_shape=Size())

Draw simplex values by reparameterizing the Gaussian log ratios.

PARAMETER DESCRIPTION
sample_shape

Independent sample dimensions preceding the batch dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Strictly positive simplex draws.

RAISES DESCRIPTION
FloatingPointError

If floating point underflow cannot represent an interior draw.

Source code in src/quivers/continuous/_additive_log_ratio.py
def rsample(self, sample_shape=torch.Size()):
    """Draw simplex values by reparameterizing the Gaussian log ratios.

    Parameters
    ----------
    sample_shape : torch.Size
        Independent sample dimensions preceding the batch dimensions.

    Returns
    -------
    Tensor
        Strictly positive simplex draws.

    Raises
    ------
    FloatingPointError
        If floating point underflow cannot represent an interior draw.
    """
    ratios = self._normal.rsample(sample_shape)
    logits = torch.zeros(
        (*ratios.shape[:-1], self.event_shape[0]),
        dtype=ratios.dtype,
        device=ratios.device,
    )
    indices = self._coordinate_indices(ratios.shape[:-1])
    values = logits.scatter(-1, indices, ratios).softmax(-1)
    if not bool((values > 0).all()):
        raise FloatingPointError(
            "AdditiveLogRatioNormal draw underflowed the simplex interior"
        )
    return values

log_prob

log_prob(value)

Score an interior simplex event, including the ALR Jacobian.

PARAMETER DESCRIPTION
value

Candidate simplex events with the trailing component axis.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Gaussian log density minus the sum of log components; negative infinity outside the simplex interior.

RAISES DESCRIPTION
ValueError

If the event has the wrong number of components.

Source code in src/quivers/continuous/_additive_log_ratio.py
def log_prob(self, value):
    """Score an interior simplex event, including the ALR Jacobian.

    Parameters
    ----------
    value : Tensor
        Candidate simplex events with the trailing component axis.

    Returns
    -------
    Tensor
        Gaussian log density minus the sum of log components; negative
        infinity outside the simplex interior.

    Raises
    ------
    ValueError
        If the event has the wrong number of components.
    """
    value = torch.as_tensor(value, dtype=self.loc.dtype, device=self.loc.device)
    if value.ndim < 1 or value.shape[-1] != self.event_shape[0]:
        raise ValueError(
            "AdditiveLogRatioNormal event has the wrong component count"
        )
    value = value.expand(
        torch.broadcast_shapes(value.shape[:-1], self.batch_shape)
        + self.event_shape
    )
    valid = (
        torch.isfinite(value).all(-1)
        & (value > 0).all(-1)
        & constraints.simplex.check(value)
    )
    safe = torch.where(
        valid[..., None], value, torch.full_like(value, 1 / value.shape[-1])
    )
    log_y = safe.log()
    reference = self.reference.expand(log_y.shape[:-1]).unsqueeze(-1)
    ratios = log_y.gather(
        -1, self._coordinate_indices(log_y.shape[:-1])
    ) - log_y.gather(-1, reference)
    score = self._normal.log_prob(ratios) - log_y.sum(-1)
    return torch.where(valid, score, torch.full_like(score, -torch.inf))

MultivariateStudentT

MultivariateStudentT(df: Tensor | float, loc: Tensor, covariance_matrix: Tensor | None = None, precision_matrix: Tensor | None = None, scale_tril: Tensor | None = None, validate_args: bool | None = None)

Bases: Distribution

A multivariate Student law with one shared radial scale per vector.

PARAMETER DESCRIPTION
df

Positive degrees of freedom, broadcast over Gaussian batch axes.

TYPE: Tensor or float

loc

Location with trailing event dimension D.

TYPE: Tensor

covariance_matrix

Exactly one Gaussian scale representation. The scale matrix is not the response covariance; the latter is df/(df-2) times the scale when df > 2. Factors follow MultivariateNormal conventions.

TYPE: Tensor or None DEFAULT: None

precision_matrix

Exactly one Gaussian scale representation. The scale matrix is not the response covariance; the latter is df/(df-2) times the scale when df > 2. Factors follow MultivariateNormal conventions.

TYPE: Tensor or None DEFAULT: None

scale_tril

Exactly one Gaussian scale representation. The scale matrix is not the response covariance; the latter is df/(df-2) times the scale when df > 2. Factors follow MultivariateNormal conventions.

TYPE: Tensor or None DEFAULT: None

validate_args

Torch argument and observation validation policy.

TYPE: bool or None DEFAULT: None

Notes

A single chi-squared variate scales every coordinate in each vector. Independent univariate Student distributions have a different joint law. The location is the response mean only for degrees of freedom above one.

Source code in src/quivers/continuous/_multivariate_student_t.py
def __init__(
    self,
    df: Tensor | float,
    loc: Tensor,
    covariance_matrix: Tensor | None = None,
    precision_matrix: Tensor | None = None,
    scale_tril: Tensor | None = None,
    validate_args: bool | None = None,
) -> None:
    df = torch.as_tensor(
        df,
        device=loc.device,
        dtype=None if isinstance(df, Tensor) else loc.dtype,
    )
    dtype = torch.promote_types(df.dtype, loc.dtype)
    for value in (covariance_matrix, precision_matrix, scale_tril):
        if value is not None:
            dtype = torch.promote_types(dtype, value.dtype)
    if not dtype.is_floating_point:
        dtype = torch.get_default_dtype()
    normal = MultivariateNormal(
        loc.to(dtype),
        covariance_matrix=None
        if covariance_matrix is None
        else covariance_matrix.to(dtype),
        precision_matrix=None
        if precision_matrix is None
        else precision_matrix.to(dtype),
        scale_tril=None if scale_tril is None else scale_tril.to(dtype),
        validate_args=validate_args,
    )
    batch = torch.broadcast_shapes(df.shape, normal.batch_shape)
    self._normal = normal.expand(batch)
    self.df = df.to(dtype).expand(batch)
    self.loc = self._normal.loc
    self.scale_tril = self._normal.scale_tril
    super().__init__(batch, normal.event_shape, validate_args=validate_args)

arg_constraints property

arg_constraints: dict[str, Constraint]

Read the checked heads without materializing covariance properties.

RETURNS DESCRIPTION
dict[str, Constraint]

Actual stored Gaussian factor and Student head constraints.

covariance_matrix property

covariance_matrix: Tensor

Return the Gaussian scale matrix, following Torch parameter names.

RETURNS DESCRIPTION
Tensor

Scale matrices with trailing shape (D,D).

precision_matrix property

precision_matrix: Tensor

Return the inverse Gaussian scale matrix.

RETURNS DESCRIPTION
Tensor

Inverse scale matrices with trailing shape (D,D).

mean property

mean: Tensor

Return the finite response mean where it exists.

RETURNS DESCRIPTION
Tensor

Location for df > 1 and NaN otherwise.

variance property

variance: Tensor

Return marginal variances with Student moment existence boundaries.

RETURNS DESCRIPTION
Tensor

Finite variances above two degrees of freedom, infinity between one and two, and NaN at or below one.

log_prob

log_prob(value: Tensor) -> Tensor

Evaluate the marginal vector density without auxiliary latent sites.

PARAMETER DESCRIPTION
value

Observations ending in the declared vector event axis.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One log density per sample and batch coordinate.

Source code in src/quivers/continuous/_multivariate_student_t.py
def log_prob(self, value: Tensor) -> Tensor:
    """Evaluate the marginal vector density without auxiliary latent sites.

    Parameters
    ----------
    value : Tensor
        Observations ending in the declared vector event axis.

    Returns
    -------
    Tensor
        One log density per sample and batch coordinate.
    """
    if self._validate_args:
        self._validate_sample(value)
    width = self.event_shape[0]
    factor = self._normal._unbroadcasted_scale_tril
    squared = _batch_mahalanobis(factor, value - self.loc)
    log_det = factor.diagonal(dim1=-2, dim2=-1).log().sum(-1)
    half = self.df / 2
    increment = torch.full_like(half, width / 2)
    return (
        _log_gamma_increment(half, increment)
        - (width / 2) * (self.df.log() + math.log(math.pi))
        - log_det
        - ((self.df + width) / 2) * torch.log1p(squared / self.df)
    )

rsample

rsample(sample_shape: Sequence[int] = Size()) -> Tensor

Draw pathwise using one radial chi-squared scale per vector.

PARAMETER DESCRIPTION
sample_shape

Leading sample axes.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws with sample, batch, and final vector event dimensions.

Source code in src/quivers/continuous/_multivariate_student_t.py
def rsample(self, sample_shape: Sequence[int] = torch.Size()) -> Tensor:
    """Draw pathwise using one radial chi-squared scale per vector.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading sample axes.

    Returns
    -------
    Tensor
        Draws with sample, batch, and final vector event dimensions.
    """
    normal = self._normal.rsample(torch.Size(sample_shape))
    radial = Chi2(self.df).rsample(torch.Size(sample_shape))
    return self.loc + (normal - self.loc) * torch.sqrt(self.df / radial)[..., None]

expand

expand(batch_shape: Sequence[int], _instance=None) -> MultivariateStudentT

Expand only batch axes while retaining the shared factor.

PARAMETER DESCRIPTION
batch_shape

Broadcast-compatible new batch dimensions.

TYPE: Size

_instance

Optional uninitialized expansion instance, following Torch.

TYPE: MultivariateStudentT or None DEFAULT: None

RETURNS DESCRIPTION
MultivariateStudentT

Expanded distribution without another matrix factorization.

Source code in src/quivers/continuous/_multivariate_student_t.py
def expand(
    self, batch_shape: Sequence[int], _instance=None
) -> MultivariateStudentT:
    """Expand only batch axes while retaining the shared factor.

    Parameters
    ----------
    batch_shape : torch.Size
        Broadcast-compatible new batch dimensions.
    _instance : MultivariateStudentT or None
        Optional uninitialized expansion instance, following Torch.

    Returns
    -------
    MultivariateStudentT
        Expanded distribution without another matrix factorization.
    """
    new = self._get_checked_instance(MultivariateStudentT, _instance)
    batch_shape = torch.Size(batch_shape)
    new._normal = self._normal.expand(batch_shape)
    new.df = self.df.expand(batch_shape)
    new.loc = new._normal.loc
    new.scale_tril = new._normal.scale_tril
    super(MultivariateStudentT, new).__init__(
        batch_shape, self.event_shape, validate_args=False
    )
    new._validate_args = self._validate_args
    return new

Multinomial

Multinomial(total_count, probs=None, logits=None, validate_args=None)

Bases: Distribution

Multinomial events with a separate trial count on each batch row.

PARAMETER DESCRIPTION
total_count

Nonnegative integer trials, exactly representable through 2**53.

TYPE: Tensor or int

probs

Finite nonnegative category weights with a positive row total.

TYPE: Tensor or Sequence[float] or None DEFAULT: None

logits

Alternative category log weights; provide exactly one representation.

TYPE: Tensor or Sequence[float] or None DEFAULT: None

validate_args

Whether to validate observation support through torch.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_multinomial.py
def __init__(self, total_count, probs=None, logits=None, validate_args=None):
    if (probs is None) == (logits is None):
        raise ValueError("Multinomial requires exactly one of probs and logits")
    vector = probs if probs is not None else logits
    self.total_count, parameter = _count_parameters(total_count, vector)
    self._from_probs = probs is not None
    self._parameter = parameter
    # Validate the original representation before zero-trial masking.
    with torch.no_grad():
        if probs is not None:
            _ValidatedCategorical(probs=parameter)
        else:
            valid = torch.isfinite(parameter) | (parameter == -torch.inf)
            demand(
                valid.all(-1) & torch.isfinite(parameter).any(-1),
                lambda: ValueError(
                    "Multinomial logits require a finite category and no NaN or positive infinity"
                ),
            )
            _ValidatedCategorical(logits=parameter)
    super().__init__(
        self.total_count.shape,
        torch.Size((parameter.shape[-1],)),
        validate_args=False,
    )
    self._validate_args = bool(validate_args)

mean property

mean

Expected category counts.

RETURNS DESCRIPTION
Tensor

Float64 counts on the batch and category axes.

variance property

variance

Marginal category variances.

RETURNS DESCRIPTION
Tensor

Float64 variances on batch and category axes.

probs

probs()

Normalized category probabilities, retaining the original zero-trial input.

RETURNS DESCRIPTION
Tensor

Probabilities on batch and category axes.

Source code in src/quivers/continuous/_multinomial.py
@lazy_property
def probs(self):
    """Normalized category probabilities, retaining the original zero-trial input.

    Returns
    -------
    Tensor
        Probabilities on batch and category axes.
    """
    return self._categorical().probs

logits

logits()

Normalized category log weights with exact structural zeros.

RETURNS DESCRIPTION
Tensor

Log probabilities on batch and category axes.

Source code in src/quivers/continuous/_multinomial.py
@lazy_property
def logits(self):
    """Normalized category log weights with exact structural zeros.

    Returns
    -------
    Tensor
        Log probabilities on batch and category axes.
    """
    return self._categorical().logits

expand

expand(batch_shape, _instance=None)

Expand parameter views while preserving category event axes.

PARAMETER DESCRIPTION
batch_shape

Requested batch shape.

TYPE: Size or Sequence[int]

_instance

Optional torch expansion instance.

TYPE: Multinomial or None DEFAULT: None

RETURNS DESCRIPTION
Multinomial

Expanded distribution with unchanged category count.

Source code in src/quivers/continuous/_multinomial.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views while preserving category event axes.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested batch shape.
    _instance : Multinomial or None
        Optional torch expansion instance.

    Returns
    -------
    Multinomial
        Expanded distribution with unchanged category count.
    """
    new = self._get_checked_instance(type(self), _instance)
    batch_shape = torch.Size(batch_shape)
    new.total_count = self.total_count.expand(batch_shape)
    new._parameter = self._parameter.expand(*batch_shape, *self.event_shape)
    new._from_probs = self._from_probs
    Distribution.__init__(new, batch_shape, self.event_shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Score whole count vectors by stable conditional binomial masses.

PARAMETER DESCRIPTION
value

Count events with the declared trailing category axis.

TYPE: Tensor or Sequence[int]

RETURNS DESCRIPTION
Tensor

One Float64 log mass per sample and batch event.

Source code in src/quivers/continuous/_multinomial.py
def log_prob(self, value):
    """Score whole count vectors by stable conditional binomial masses.

    Parameters
    ----------
    value : Tensor or Sequence[int]
        Count events with the declared trailing category axis.

    Returns
    -------
    Tensor
        One Float64 log mass per sample and batch event.
    """
    point, n, valid = _count_event(value, self.total_count, self.event_shape[0])
    active = valid & (n > 0)
    categorical = self._categorical(active)
    n = torch.where(valid, n, 0.0)
    if self.event_shape[0] == 1:
        return torch.where(valid, n * 0 + categorical.probs.sum(-1) * 0, -torch.inf)
    remaining = _remaining_counts(point, n)
    k = point[..., :-1]
    if self._from_probs:
        probabilities = categorical.probs
        tail = probabilities.flip(-1).cumsum(-1).flip(-1)
        denom = tail[..., :-1]
        p = torch.where(
            denom > 0,
            probabilities[..., :-1] / torch.where(denom > 0, denom, 1.0),
            0.0,
        )
        scores = ClosedBinomial(remaining, probs=p, validate_args=False).log_prob(k)
    else:
        logits = cast(Tensor, categorical.logits)
        tail = _log_tails(logits)
        active = torch.isfinite(tail[..., :-1])
        base = torch.where(active, tail[..., :-1], 0.0)
        log_p = logits[..., :-1] - base
        log_q = tail[..., 1:] - base
        ordinary = active & torch.isfinite(log_p) & torch.isfinite(log_q)
        scores = _binomial_log_mass(
            k,
            remaining,
            torch.where(ordinary, log_p, -0.6931471805599453),
            torch.where(ordinary, log_q, -0.6931471805599453),
        )
        left = torch.where(
            k == 0, 0.0, k * torch.where(torch.isfinite(log_p), log_p, 0.0)
        )
        right = torch.where(
            remaining == k,
            0.0,
            (remaining - k) * torch.where(torch.isfinite(log_q), log_q, 0.0),
        )
        endpoint = left + right
        impossible = ((k > 0) & ~torch.isfinite(log_p)) | (
            (remaining > k) & ~torch.isfinite(log_q)
        )
        endpoint = torch.where(impossible, -torch.inf, endpoint)
        scores = torch.where(ordinary, scores, endpoint)
    return torch.where(valid, scores.sum(-1), -torch.inf)

sample

sample(sample_shape: Size | Sequence[int] = Size())

Draw Int64 events in O(categories times rows) work.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 events with exactly the requested trial totals.

Source code in src/quivers/continuous/_multinomial.py
def sample(self, sample_shape: torch.Size | Sequence[int] = torch.Size()):
    """Draw Int64 events in O(categories times rows) work.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Int64 events with exactly the requested trial totals.
    """
    with torch.no_grad():
        return _multinomial_sample(
            self.total_count,
            self._categorical(self.total_count > 0).probs,
            sample_shape,
        )

DirichletMultinomial

DirichletMultinomial(total_count, concentration, validate_args=None)

Bases: Distribution

Multinomial events with Dirichlet-distributed category probabilities.

PARAMETER DESCRIPTION
total_count

Nonnegative integer trials through 2**53 on the batch axes.

TYPE: Tensor or int

concentration

Finite strictly positive category concentrations.

TYPE: Tensor or Sequence[float]

validate_args

Whether torch validates normalized parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_multinomial.py
def __init__(self, total_count, concentration, validate_args=None):
    self.total_count, self.concentration = _count_parameters(
        total_count, concentration
    )
    demand(
        torch.isfinite(self.concentration) & (self.concentration > 0),
        lambda: ValueError(
            "DirichletMultinomial concentrations must be finite and positive"
        ),
    )
    demand(
        torch.isfinite(self.concentration.sum(-1)),
        lambda: ValueError(
            "DirichletMultinomial concentration totals exceed Float64 capacity"
        ),
    )
    super().__init__(
        self.total_count.shape,
        torch.Size((self.concentration.shape[-1],)),
        validate_args=validate_args,
    )

mean property

mean

Expected category counts.

RETURNS DESCRIPTION
Tensor

Float64 counts including exact zero-trial rows.

variance property

variance

Marginal category variances, including Dirichlet overdispersion.

RETURNS DESCRIPTION
Tensor

Float64 marginal variances.

expand

expand(batch_shape, _instance=None)

Expand trials and concentration views without merging event axes.

PARAMETER DESCRIPTION
batch_shape

Requested batch shape.

TYPE: Size or Sequence[int]

_instance

Optional torch expansion instance.

TYPE: DirichletMultinomial or None DEFAULT: None

RETURNS DESCRIPTION
DirichletMultinomial

Expanded count-vector distribution.

Source code in src/quivers/continuous/_multinomial.py
def expand(self, batch_shape, _instance=None):
    """Expand trials and concentration views without merging event axes.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested batch shape.
    _instance : DirichletMultinomial or None
        Optional torch expansion instance.

    Returns
    -------
    DirichletMultinomial
        Expanded count-vector distribution.
    """
    new = self._get_checked_instance(type(self), _instance)
    batch_shape = torch.Size(batch_shape)
    new.total_count = self.total_count.expand(batch_shape)
    new.concentration = self.concentration.expand(*batch_shape, *self.event_shape)
    Distribution.__init__(new, batch_shape, self.event_shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Score the event using its exact conditional beta-binomial factorization.

PARAMETER DESCRIPTION
value

Count vectors on the trailing category axis.

TYPE: Tensor or Sequence[int]

RETURNS DESCRIPTION
Tensor

Float64 log masses on the sample and batch axes.

Source code in src/quivers/continuous/_multinomial.py
def log_prob(self, value):
    """Score the event using its exact conditional beta-binomial factorization.

    Parameters
    ----------
    value : Tensor or Sequence[int]
        Count vectors on the trailing category axis.

    Returns
    -------
    Tensor
        Float64 log masses on the sample and batch axes.
    """
    point, n, valid = _count_event(value, self.total_count, self.event_shape[0])
    n = torch.where(valid, n, 0.0)
    concentration = torch.where((n > 0).unsqueeze(-1), self.concentration, 1.0)
    if self.event_shape[0] == 1:
        return torch.where(valid, n * 0 + concentration.sum(-1) * 0, -torch.inf)
    tail = concentration.flip(-1).cumsum(-1).flip(-1)
    scores = _beta_binomial_log_mass(
        point[..., :-1],
        _remaining_counts(point, n),
        concentration[..., :-1],
        tail[..., 1:],
    )
    return torch.where(valid, scores.sum(-1), -torch.inf)

sample

sample(sample_shape: Size | Sequence[int] = Size())

Draw Dirichlet weights and use the shared heterogeneous-trial sampler.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 count events with exact trial totals.

Source code in src/quivers/continuous/_multinomial.py
def sample(self, sample_shape: torch.Size | Sequence[int] = torch.Size()):
    """Draw Dirichlet weights and use the shared heterogeneous-trial sampler.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Int64 count events with exact trial totals.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        totals = self.total_count.expand(shape[:-1])
        concentration = self.concentration.expand(shape)
        active = totals > 0
        result = torch.zeros(shape, dtype=torch.int64, device=totals.device)
        if bool(active.any()):
            probabilities = _dirichlet_weights(concentration[active])
            result[active] = _multinomial_sample(totals[active], probabilities)
        return result

DiscreteWeibull

DiscreteWeibull(probs, concentration, validate_args=None, *, moment_rtol=1e-10, moment_max_terms=262144)

Bases: Distribution

Counts with survival P(Y >= k) = probs**(k**concentration).

PARAMETER DESCRIPTION
probs

Survival parameter in [0, 1), with zero giving the point mass at zero.

TYPE: Tensor or float

concentration

Strictly positive power parameter.

TYPE: Tensor or float

validate_args

Whether to validate distribution parameters.

TYPE: bool or None DEFAULT: None

moment_rtol

Relative tolerance certified by omitted-moment integral bounds.

TYPE: float DEFAULT: 1e-10

moment_max_terms

Maximum number of count cells used for a moment calculation.

TYPE: int DEFAULT: 262144

Notes

Density and inverse-transform sampling require constant work per row. Moments use adaptive blocks and analytic upper bounds on the omitted tails. Failure to certify the requested tolerance raises explicitly. Native count arithmetic uses Float64 and integer samples use Int64.

Source code in src/quivers/continuous/_discrete_weibull.py
def __init__(
    self,
    probs,
    concentration,
    validate_args=None,
    *,
    moment_rtol=1e-10,
    moment_max_terms=262144,
):
    if (
        not 0 < moment_rtol < 1
        or not isinstance(moment_max_terms, int)
        or moment_max_terms < 1
    ):
        raise ValueError(
            "DiscreteWeibull moment tolerance must lie in (0,1) and term budget must be positive"
        )
    self.probs, self.concentration = _broadcast_count_parameters(
        probs, concentration
    )
    self.moment_rtol = moment_rtol
    self.moment_max_terms = moment_max_terms
    super().__init__(self.probs.shape, validate_args=validate_args)

mean property

mean

Compute the mean with an analytic omitted-tail error bound.

RETURNS DESCRIPTION
Tensor

Float64 response means within the configured relative tolerance.

variance property

variance

Compute variance without subtracting two large raw moments.

RETURNS DESCRIPTION
Tensor

Float64 variances within the configured relative tolerance.

expand

expand(batch_shape, _instance=None)

Expand the parameter views and retain the moment resource policy.

PARAMETER DESCRIPTION
batch_shape

Target batch dimensions.

TYPE: Size

_instance

Optional reusable instance.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
DiscreteWeibull

Expanded distribution.

Source code in src/quivers/continuous/_discrete_weibull.py
def expand(self, batch_shape, _instance=None):
    """Expand the parameter views and retain the moment resource policy.

    Parameters
    ----------
    batch_shape : torch.Size
        Target batch dimensions.
    _instance : Distribution or None
        Optional reusable instance.

    Returns
    -------
    DiscreteWeibull
        Expanded distribution.
    """
    new = self._get_checked_instance(DiscreteWeibull, _instance)
    shape = torch.Size(batch_shape)
    new.probs, new.concentration = (
        self.probs.expand(shape),
        self.concentration.expand(shape),
    )
    new.moment_rtol, new.moment_max_terms = self.moment_rtol, self.moment_max_terms
    super(DiscreteWeibull, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate a count mass in Float64.

PARAMETER DESCRIPTION
value

Candidate integer counts.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log mass, negative infinity outside the support.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_prob(self, value):
    """Evaluate a count mass in Float64.

    Parameters
    ----------
    value : Tensor
        Candidate integer counts.

    Returns
    -------
    Tensor
        Log mass, negative infinity outside the support.
    """
    _check_count_observation_source(value)
    return _log_mass(self.probs, self.concentration, value.double())

log_interval_mass

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

Evaluate an integer interval without subtracting rounded tail values.

PARAMETER DESCRIPTION
low

Real endpoints; None leaves a side unbounded.

TYPE: Tensor or float or None

high

Real endpoints; None leaves a side unbounded.

TYPE: Tensor or float or None

lower_closed

Endpoint membership, optionally varying across batch rows.

TYPE: bool or Tensor DEFAULT: True

upper_closed

Endpoint membership, optionally varying across batch rows.

TYPE: bool or Tensor DEFAULT: True

RETURNS DESCRIPTION
Tensor

Exact factored log probabilities on the distribution batch.

RAISES DESCRIPTION
ValueError

If an endpoint is NaN.

TypeError

If endpoint membership is not Boolean.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Evaluate an integer interval without subtracting rounded tail values.

    Parameters
    ----------
    low, high : Tensor or float or None
        Real endpoints; None leaves a side unbounded.
    lower_closed, upper_closed : bool or Tensor
        Endpoint membership, optionally varying across batch rows.

    Returns
    -------
    Tensor
        Exact factored log probabilities on the distribution batch.

    Raises
    ------
    ValueError
        If an endpoint is NaN.
    TypeError
        If endpoint membership is not Boolean.
    """
    from quivers.continuous._interval import _closed_flag

    lower_closed = _closed_flag(lower_closed, "lower_closed")
    upper_closed = _closed_flag(upper_closed, "upper_closed")
    lower = torch.as_tensor(
        -torch.inf if low is None else low,
        dtype=torch.float64,
        device=self.probs.device,
    )
    upper = torch.as_tensor(
        torch.inf if high is None else high,
        dtype=torch.float64,
        device=self.probs.device,
    )
    demand(
        ~torch.isnan(lower),
        lambda: ValueError("interval endpoints must not be NaN"),
    )
    demand(
        ~torch.isnan(upper),
        lambda: ValueError("interval endpoints must not be NaN"),
    )
    first = torch.where(
        torch.as_tensor(lower_closed, device=lower.device),
        lower.ceil(),
        lower.floor() + 1,
    ).clamp_min(0)
    last = torch.where(
        torch.as_tensor(upper_closed, device=upper.device),
        upper.floor(),
        upper.ceil() - 1,
    )
    valid = torch.isfinite(first) & (last >= first)
    first, last = torch.where(valid, first, 0.0), torch.where(valid, last, 0.0)
    mass = _integer_interval_log_mass(self.probs, self.concentration, first, last)
    return torch.where(valid, mass, -torch.inf)

log_cdf

log_cdf(value)

Evaluate probability at or below a real count bound in log space.

PARAMETER DESCRIPTION
value

Real count bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log cumulative probabilities.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_cdf(self, value):
    """Evaluate probability at or below a real count bound in log space.

    Parameters
    ----------
    value : Tensor
        Real count bounds.

    Returns
    -------
    Tensor
        Log cumulative probabilities.
    """
    return self._log_tails(value)[0]

log_survival_function

log_survival_function(value)

Evaluate probability strictly above a real count bound in log space.

PARAMETER DESCRIPTION
value

Real count bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log strict survival probabilities.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_survival_function(self, value):
    """Evaluate probability strictly above a real count bound in log space.

    Parameters
    ----------
    value : Tensor
        Real count bounds.

    Returns
    -------
    Tensor
        Log strict survival probabilities.
    """
    return self._log_tails(value)[1]

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Real count bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Cumulative probabilities.

Source code in src/quivers/continuous/_discrete_weibull.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Real count bounds.

    Returns
    -------
    Tensor
        Cumulative probabilities.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Invert the staircase cumulative distribution.

PARAMETER DESCRIPTION
value

Probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Float64 count quantiles, positive infinity at probability one except for the degenerate-zero law.

RAISES DESCRIPTION
RuntimeError

If a finite requested quantile exceeds exact Float64 count capacity.

Source code in src/quivers/continuous/_discrete_weibull.py
def icdf(self, value):
    """Invert the staircase cumulative distribution.

    Parameters
    ----------
    value : Tensor
        Probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Float64 count quantiles, positive infinity at probability one
        except for the degenerate-zero law.

    Raises
    ------
    RuntimeError
        If a finite requested quantile exceeds exact Float64 count capacity.
    """
    value = value.double()
    if self._validate_args:
        _check_probability(value)
    interior = (value > 0) & (value < 1) & (self.probs > 0)
    probability = torch.where(interior, value, 0.5)
    q = torch.where(self.probs > 0, self.probs, 0.5)
    log_root = (
        (-torch.log1p(-probability)).log() - (-q.log()).log()
    ) / self.concentration
    root = log_root.exp()
    candidate = (root.ceil() - 1).clamp_min(0)
    _require_sample_capacity(torch.where(interior, candidate, 0.0))
    candidate = torch.where(
        self.cdf(candidate) < probability, candidate + 1, candidate
    )
    previous = (candidate - 1).clamp_min(0)
    candidate = torch.where(
        (candidate > 0) & (self.cdf(previous) >= probability), previous, candidate
    )
    result = torch.where(interior, candidate, 0.0)
    return torch.where((value == 1) & (self.probs > 0), torch.inf, result)

sample

sample(sample_shape=Size())

Draw integer counts by a vectorized exponential transform.

PARAMETER DESCRIPTION
sample_shape

Dimensions prepended to the parameter batch.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 counts on the parameters' device.

RAISES DESCRIPTION
RuntimeError

If a generated count exceeds exact Float64 integer capacity.

Source code in src/quivers/continuous/_discrete_weibull.py
def sample(self, sample_shape=torch.Size()):
    """Draw integer counts by a vectorized exponential transform.

    Parameters
    ----------
    sample_shape : torch.Size
        Dimensions prepended to the parameter batch.

    Returns
    -------
    Tensor
        Int64 counts on the parameters' device.

    Raises
    ------
    RuntimeError
        If a generated count exceeds exact Float64 integer capacity.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        exponential = torch.empty(
            shape, dtype=self.probs.dtype, device=self.probs.device
        ).exponential_()
        q = torch.where(self.probs > 0, self.probs, 0.5)
        log_count = (exponential.log() - (-q.log()).log()) / self.concentration
        count = torch.where(self.probs > 0, log_count.exp().floor(), 0.0)
        return _require_sample_capacity(count).long()

Wiener

Wiener(boundary: Tensor | float, ndt: Tensor | float, bias: Tensor | float, drift: Tensor | float, validate_args: bool | None = False, *, max_proposals: int = 10000, max_terms: int = 64, max_precision: int = 192)

Bases: Distribution

Joint signed response-time law for two absorbing diffusion boundaries.

PARAMETER DESCRIPTION
boundary

Positive boundary separation, with Brownian variance fixed to one.

TYPE: Tensor or float

ndt

Nonnegative delay added to decision time.

TYPE: Tensor or float

bias

Starting position as a fraction of separation, strictly between zero and one.

TYPE: Tensor or float

drift

Finite drift towards the upper boundary.

TYPE: Tensor or float

validate_args

Whether off-support observations raise rather than score as -infinity. Parameter validation is always performed.

TYPE: bool or None DEFAULT: False

max_proposals

Finite rejection, series, and decimal precision budgets. Exhaustion raises; the sampler never substitutes an approximate draw.

TYPE: int DEFAULT: 10000

max_terms

Finite rejection, series, and decimal precision budgets. Exhaustion raises; the sampler never substitutes an approximate draw.

TYPE: int DEFAULT: 10000

max_precision

Finite rejection, series, and decimal precision budgets. Exhaustion raises; the sampler never substitutes an approximate draw.

TYPE: int DEFAULT: 10000

Notes

Positive observations encode upper hits and negative observations lower hits. The likelihood is joint in time and decision, without conditioning on the chosen boundary. Scores and samples use Float64; input gradients propagate to the original parameter dtype. Sampling is not reparameterized. Its exact-arithmetic construction has acceptance probability at least 1/2; numerical acceptance decisions use outward-rounded series enclosures.

Source code in src/quivers/continuous/_wiener.py
def __init__(
    self,
    boundary: Tensor | float,
    ndt: Tensor | float,
    bias: Tensor | float,
    drift: Tensor | float,
    validate_args: bool | None = False,
    *,
    max_proposals: int = 10000,
    max_terms: int = 64,
    max_precision: int = 192,
) -> None:
    values = (boundary, ndt, bias, drift)
    if any(
        isinstance(v, bool)
        or isinstance(v, Tensor)
        and (v.dtype == torch.bool or v.is_complex())
        for v in values
    ):
        raise ValueError("Wiener parameters must be real and nonboolean")
    device = next(
        (v.device for v in values if isinstance(v, Tensor)), torch.device("cpu")
    )
    tensors = broadcast_all(
        *(torch.as_tensor(v, dtype=torch.float64, device=device) for v in values)
    )
    self.boundary, self.ndt, self.bias, self.drift = tensors
    for tensor in tensors:
        demand(
            torch.isfinite(tensor),
            lambda: ValueError("Wiener parameters must be finite"),
        )
    demand(
        (self.boundary > 0) & (self.ndt >= 0) & (self.bias > 0) & (self.bias < 1),
        lambda: ValueError("Wiener requires boundary>0, ndt>=0, and 0<bias<1"),
    )
    budgets = (max_proposals, max_terms, max_precision)
    if any(isinstance(v, bool) or not isinstance(v, int) or v < 1 for v in budgets):
        raise ValueError("Wiener numerical budgets must be positive integers")
    self.max_proposals, self.max_terms, self.max_precision = budgets
    super().__init__(self.boundary.shape, torch.Size(), validate_args=validate_args)

arg_constraints property

arg_constraints: dict[str, Constraint]

Return the domains of diffusion parameters.

RETURNS DESCRIPTION
dict of str to Constraint

Positive separation, nonnegative delay, open-unit bias, real drift.

support property

support: _SignedSupport

Return the signed reaction-time constraint.

RETURNS DESCRIPTION
_SignedSupport

Absolute reaction time strictly above nondecision delay.

choice_probs property

choice_probs: Tensor

Return lower/upper boundary probabilities along a final length-two axis.

RETURNS DESCRIPTION
Tensor

Choice probabilities with axes batch x (lower, upper).

mean property

mean: Tensor

Return the mean signed reaction time.

RETURNS DESCRIPTION
Tensor

Positive upper-choice and negative lower-choice joint mean.

variance property

variance: Tensor

Return signed reaction-time variance using a stable mixture formula.

RETURNS DESCRIPTION
Tensor

Variance of signed joint reaction times.

mean_response_time property

mean_response_time: Tensor

Return mean absolute reaction time, including nondecision delay.

RETURNS DESCRIPTION
Tensor

Expected unsigned response time.

variance_response_time property

variance_response_time: Tensor

Return unsigned reaction-time variance.

RETURNS DESCRIPTION
Tensor

Variance of the magnitude of signed joint samples.

log_prob

log_prob(value: Tensor | float) -> Tensor

Score a signed time without losing the probability of its decision.

PARAMETER DESCRIPTION
value

Signed reaction time, broadcastable with parameter batch axes.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Float64 joint log density, negative infinity outside support when observation validation is disabled.

RAISES DESCRIPTION
ValueError

If observations are boolean or complex, or normalized times exceed floating-point arithmetic capacity.

Source code in src/quivers/continuous/_wiener.py
def log_prob(self, value: Tensor | float) -> Tensor:
    """Score a signed time without losing the probability of its decision.

    Parameters
    ----------
    value : Tensor or float
        Signed reaction time, broadcastable with parameter batch axes.

    Returns
    -------
    Tensor
        Float64 joint log density, negative infinity outside support when
        observation validation is disabled.

    Raises
    ------
    ValueError
        If observations are boolean or complex, or normalized times exceed
        floating-point arithmetic capacity.
    """
    if (
        isinstance(value, bool)
        or isinstance(value, Tensor)
        and (value.dtype == torch.bool or value.is_complex())
    ):
        raise ValueError("Wiener observations must be real and nonboolean")
    point = torch.as_tensor(value, dtype=torch.float64, device=self.boundary.device)
    if self._validate_args:
        self._validate_sample(point)
    valid = self.support.check(point)
    decision = torch.where(valid, point.abs() - self.ndt, self.boundary.square())
    time = decision / self.boundary / self.boundary
    demand(
        torch.isfinite(time) & (time > 0),
        lambda: ValueError(
            "Wiener normalized time exceeds floating-point capacity"
        ),
    )
    upper = point > 0
    w = torch.where(upper, 1 - self.bias, self.bias)
    c = torch.where(upper, self.bias, 1 - self.bias)
    toward = torch.where(upper, self.drift, -self.drift)
    log_distance = self.boundary.log() + w.log()
    # Completing the square avoids cancellation between the drift tilt
    # and the very small-time zero-drift kernel for large drifts.
    standardized = (self.boundary / decision.sqrt()) * w - toward * decision.sqrt()
    result = (
        log_distance
        - 0.5 * math.log(2 * math.pi)
        - 1.5 * decision.log()
        - standardized.square() / 2
        + _log_ratio(time, w, c)
    )
    return torch.where(valid, result, -torch.inf)

sample

sample(sample_shape: Sequence[int] = Size()) -> Tensor

Draw signed reaction times using certified first-passage rejection.

PARAMETER DESCRIPTION
sample_shape

Leading independent sample dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Float64 signed times, with sample and parameter-batch dimensions.

Source code in src/quivers/continuous/_wiener.py
@torch.no_grad()
def sample(self, sample_shape: Sequence[int] = torch.Size()) -> Tensor:
    """Draw signed reaction times using certified first-passage rejection.

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

    Returns
    -------
    Tensor
        Float64 signed times, with sample and parameter-batch dimensions.
    """
    shape = self._extended_shape(torch.Size(sample_shape))
    output = torch.empty(shape, dtype=torch.float64, device="cpu")
    if output.numel() == 0:
        return output.to(self.boundary.device)
    parameters = [
        v.detach().cpu().reshape(-1).tolist()
        for v in (self.boundary, self.ndt, self.bias, self.drift)
    ]
    rows = [
        (parameters[0][i], parameters[1][i], parameters[2][i], parameters[3][i])
        for i in range(self.boundary.numel())
    ]
    rng = _TorchRandom()
    flat = output.reshape(-1)
    for i in range(flat.numel()):
        flat[i] = _draw(
            *rows[i % len(rows)],
            rng,
            max_proposals=self.max_proposals,
            max_terms=self.max_terms,
            max_precision=self.max_precision,
        )
    return output.to(self.boundary.device)

expand

expand(batch_shape: Size | Sequence[int], _instance: Wiener | None = None) -> Wiener

Expand diffusion parameter views without copying data.

PARAMETER DESCRIPTION
batch_shape

New batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional preallocated distribution instance.

TYPE: Wiener or None DEFAULT: None

RETURNS DESCRIPTION
Wiener

Distribution with broadcast parameter views and unchanged budgets.

Source code in src/quivers/continuous/_wiener.py
def expand(
    self, batch_shape: torch.Size | Sequence[int], _instance: Wiener | None = None
) -> Wiener:
    """Expand diffusion parameter views without copying data.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        New batch dimensions.
    _instance : Wiener or None
        Optional preallocated distribution instance.

    Returns
    -------
    Wiener
        Distribution with broadcast parameter views and unchanged budgets.
    """
    new = self._get_checked_instance(Wiener, _instance)
    batch_shape = torch.Size(batch_shape)
    for name in ("boundary", "ndt", "bias", "drift"):
        setattr(new, name, getattr(self, name).expand(batch_shape))
    new.max_proposals, new.max_terms, new.max_precision = (
        self.max_proposals,
        self.max_terms,
        self.max_precision,
    )
    super(Wiener, new).__init__(batch_shape, torch.Size(), validate_args=False)
    new._validate_args = self._validate_args
    return new

ZeroInflatedAsymmetricLaplace

ZeroInflatedAsymmetricLaplace(zero_prob, loc, scale, quantile, validate_args=None)

Bases: Distribution

Structural zeros and a continuous asymmetric Laplace response.

PARAMETER DESCRIPTION
zero_prob

Probability of the atom at zero, including zero and one.

TYPE: Tensor or float

loc

Quantile location of the continuous component.

TYPE: Tensor or float

scale

Positive component scale in the check-loss parameterization.

TYPE: Tensor or float

quantile

Component quantile strictly between zero and one.

TYPE: Tensor or float

validate_args

Whether to validate distribution parameters.

TYPE: bool or None DEFAULT: None

Notes

Density is relative to the sum of a zero atom and Lebesgue measure: the continuous density does not contribute to the mass at zero. Sampling selects the mixture branch before sampling its component.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def __init__(self, zero_prob, loc, scale, quantile, validate_args=None):
    self.zero_prob, self.loc, self.scale, self.quantile = broadcast_all(
        zero_prob, loc, scale, quantile
    )
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Expected mixed response.

RETURNS DESCRIPTION
Tensor

Component mean multiplied by its mixture probability.

variance property

variance

Variance including uncertainty about the mixture branch.

RETURNS DESCRIPTION
Tensor

Component variance and between-component mean contribution.

expand

expand(batch_shape, _instance=None)

Expand parameter views over a new batch.

PARAMETER DESCRIPTION
batch_shape

Target broadcast batch dimensions.

TYPE: Size

_instance

Optional reusable distribution instance.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
ZeroInflatedAsymmetricLaplace

Distribution with expanded parameter views.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views over a new batch.

    Parameters
    ----------
    batch_shape : torch.Size
        Target broadcast batch dimensions.
    _instance : Distribution or None
        Optional reusable distribution instance.

    Returns
    -------
    ZeroInflatedAsymmetricLaplace
        Distribution with expanded parameter views.
    """
    new = self._get_checked_instance(ZeroInflatedAsymmetricLaplace, _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(ZeroInflatedAsymmetricLaplace, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate the zero atom or continuous component density.

PARAMETER DESCRIPTION
value

Real responses, broadcastable with the parameter batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log atom mass at zero and log Lebesgue density elsewhere.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def log_prob(self, value):
    """Evaluate the zero atom or continuous component density.

    Parameters
    ----------
    value : Tensor
        Real responses, broadcastable with the parameter batch.

    Returns
    -------
    Tensor
        Log atom mass at zero and log Lebesgue density elsewhere.
    """
    finite = torch.isfinite(value)
    atom = value == 0
    point = torch.where(finite, value, 0.0)
    probability = torch.where(atom & finite, self.zero_prob, 1.0)
    at_zero = probability.log()
    ordinary_probability = torch.where(~atom & finite, self.zero_prob, 0.0)
    ordinary = torch.log1p(-ordinary_probability) + self._component().log_prob(
        point
    )
    return torch.where(finite, torch.where(atom, at_zero, ordinary), -torch.inf)

log_cdf

log_cdf(value)

Evaluate log probability at or below a response.

PARAMETER DESCRIPTION
value

Real response bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log cumulative probabilities, including the atom at zero.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def log_cdf(self, value):
    """Evaluate log probability at or below a response.

    Parameters
    ----------
    value : Tensor
        Real response bounds.

    Returns
    -------
    Tensor
        Log cumulative probabilities, including the atom at zero.
    """
    return self._log_tails(value)[0]

log_survival_function

log_survival_function(value)

Evaluate log probability strictly above a response.

PARAMETER DESCRIPTION
value

Real response bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log survival probabilities, excluding the atom at zero.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def log_survival_function(self, value):
    """Evaluate log probability strictly above a response.

    Parameters
    ----------
    value : Tensor
        Real response bounds.

    Returns
    -------
    Tensor
        Log survival probabilities, excluding the atom at zero.
    """
    return self._log_tails(value)[1]

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Real response bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Cumulative probabilities.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Real response bounds.

    Returns
    -------
    Tensor
        Cumulative probabilities.
    """
    return (1 - self.zero_prob) * self._component().cdf(value) + self.zero_prob * (
        value >= 0
    ).to(self.loc.dtype)

icdf

icdf(value)

Invert the continuous tails and the jump at zero.

PARAMETER DESCRIPTION
value

Probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Generalized quantiles, with zero throughout the atom's jump.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def icdf(self, value):
    """Invert the continuous tails and the jump at zero.

    Parameters
    ----------
    value : Tensor
        Probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Generalized quantiles, with zero throughout the atom's jump.
    """
    if self._validate_args:
        _check_probability(value)
    value, zero_prob = torch.broadcast_tensors(value, self.zero_prob)
    base = self._component()
    component_mass = 1 - zero_prob
    left = component_mass * base.cdf(torch.zeros_like(value))
    right = left + zero_prob
    atom = (value >= left) & (value <= right)
    degenerate = zero_prob == 1
    denominator = torch.where(degenerate, 1.0, component_mass)
    transformed = torch.where(value <= left, value, value - zero_prob) / denominator
    endpoint = (value == 0) | (value == 1)
    transformed = torch.where(atom | degenerate | endpoint, 0.5, transformed)
    result = torch.where(atom | degenerate, 0.0, base.icdf(transformed))
    result = torch.where((value == 0) & ~degenerate, -torch.inf, result)
    return torch.where((value == 1) & ~degenerate, torch.inf, result)

sample

sample(sample_shape=Size())

Select branches before sampling active continuous responses.

PARAMETER DESCRIPTION
sample_shape

Dimensions prepended to the parameter batch.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Floating responses, including exact structural zeros.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def sample(self, sample_shape=torch.Size()):
    """Select branches before sampling active continuous responses.

    Parameters
    ----------
    sample_shape : torch.Size
        Dimensions prepended to the parameter batch.

    Returns
    -------
    Tensor
        Floating responses, including exact structural zeros.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        active = torch.rand(
            shape, dtype=self.loc.dtype, device=self.loc.device
        ) >= self.zero_prob.expand(shape)
        result = torch.zeros(shape, dtype=self.loc.dtype, device=self.loc.device)
        if bool(active.any()):
            component = AsymmetricLaplace(
                self.loc.expand(shape)[active],
                self.scale.expand(shape)[active],
                self.quantile.expand(shape)[active],
                validate_args=False,
            )
            result[active] = component.sample()
        return result

ShiftedLogNormal

ShiftedLogNormal(loc, scale, shift, validate_args=None)

Bases: Distribution

A lognormal response plus a nonnegative location shift.

PARAMETER DESCRIPTION
loc

Mean of the underlying normal log response.

TYPE: Tensor or float

scale

Positive standard deviation of the underlying normal.

TYPE: Tensor or float

shift

Nonnegative lower support endpoint.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_shape_families.py
def __init__(self, loc, scale, shift, validate_args=None):
    self.loc, self.scale, self.shift = broadcast_all(loc, scale, shift)
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

support

support()

Return the parameter-dependent response support.

RETURNS DESCRIPTION
Constraint

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
@constraints.dependent_property(is_discrete=False, event_dim=0)
def support(self):
    """Return the parameter-dependent response support.

    Returns
    -------
    constraints.Constraint
        Broadcast result with the parameter device and dtype.
    """
    return constraints.greater_than(self.shift)

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(ShiftedLogNormal, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    _, inside, z, safe = self._standardized(value)
    result = (
        -0.5 * z.square() - self.scale.log() - safe.log() - 0.91893853320467274178
    )
    return torch.where(inside, result, -torch.inf)

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    difference, inside, z, _ = self._standardized(value)
    return torch.where(
        inside,
        torch.special.log_ndtr(z),
        torch.where(difference > 0, 0.0, -torch.inf),
    )

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    difference, inside, z, _ = self._standardized(value)
    return torch.where(
        inside,
        torch.special.log_ndtr(-z),
        torch.where(difference > 0, -torch.inf, 0.0),
    )

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    return self.shift + torch.exp(
        self.loc + self.scale * torch.special.ndtri(value)
    )

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z = torch.randn(
        self._extended_shape(sample_shape),
        dtype=self.loc.dtype,
        device=self.loc.device,
    )
    return self.shift + torch.exp(self.loc + self.scale * z)

Frechet

Frechet(scale, concentration, validate_args=None)

Bases: Distribution

Frechet distribution on positive responses.

PARAMETER DESCRIPTION
scale

Positive response scale.

TYPE: Tensor or float

concentration

Positive tail shape. The first moment exists above one and the second moment above two.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_shape_families.py
def __init__(self, scale, concentration, validate_args=None):
    self.scale, self.concentration = broadcast_all(scale, concentration)
    super().__init__(self.scale.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    new.scale, new.concentration = (
        self.scale.expand(shape),
        self.concentration.expand(shape),
    )
    super(Frechet, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    inside, ratio = self._log_ratio(value)
    a = self.concentration
    result = a.log() - self.scale.log() - (a + 1) * ratio - torch.exp(-a * ratio)
    return torch.where(inside, result, -torch.inf)

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    inside, ratio = self._log_ratio(value)
    result = -torch.exp(-self.concentration * ratio)
    return torch.where(inside, result, torch.where(value > 0, 0.0, -torch.inf))

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    inside, ratio = self._log_ratio(value)
    log_t = -self.concentration * ratio
    result = _log1mexp_neg_exp(log_t)
    return torch.where(inside, result, torch.where(value > 0, -torch.inf, 0.0))

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    return self.scale * torch.exp(-torch.log(-value.log()) / self.concentration)

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    exponential = torch.empty(
        self._extended_shape(sample_shape),
        dtype=self.scale.dtype,
        device=self.scale.device,
    ).exponential_()
    return self.scale * torch.exp(-exponential.log() / self.concentration)

GeneralizedExtremeValue

GeneralizedExtremeValue(loc, scale, concentration, validate_args=None)

Bases: Distribution

Generalized extreme-value law with a differentiable Gumbel limit.

PARAMETER DESCRIPTION
loc

Response location, distinct from the expectation.

TYPE: Tensor or float

scale

Positive scale.

TYPE: Tensor or float

concentration

Real extreme-value shape; zero gives Gumbel. SciPy's genextreme uses the opposite sign for its shape parameter.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_shape_families.py
def __init__(self, loc, scale, concentration, validate_args=None):
    self.loc, self.scale, self.concentration = broadcast_all(
        loc, scale, concentration
    )
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

support

support()

Return the parameter-dependent response support.

RETURNS DESCRIPTION
Constraint

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
@constraints.dependent_property(is_discrete=False, event_dim=0)
def support(self):
    """Return the parameter-dependent response support.

    Returns
    -------
    constraints.Constraint
        Broadcast result with the parameter device and dtype.
    """
    c = self.concentration
    safe = torch.where(c != 0, c, torch.ones_like(c))
    endpoint = self.loc - self.scale / safe
    return constraints.interval(
        torch.where(c > 0, endpoint, -torch.inf),
        torch.where(c < 0, endpoint, torch.inf),
    )

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(GeneralizedExtremeValue, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z, inside, r = self._transformed(value)
    result = -self.scale.log() - (1 + self.concentration) * r - torch.exp(-r)
    endpoint = (self.concentration < 0) & (1 + self.concentration * z == 0)
    limit = torch.where(
        self.concentration == -1,
        -self.scale.log(),
        torch.where(self.concentration < -1, torch.inf, -torch.inf),
    )
    return torch.where(inside, result, torch.where(endpoint, limit, -torch.inf))

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z, inside, r = self._transformed(value)
    result = -torch.exp(-r)
    upper = (self.concentration < 0) & (1 + self.concentration * z <= 0) | (
        z == torch.inf
    )
    return torch.where(inside, result, torch.where(upper, 0.0, -torch.inf))

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z, inside, r = self._transformed(value)
    result = _log1mexp_neg_exp(-r)
    upper = (self.concentration < 0) & (1 + self.concentration * z <= 0) | (
        z == torch.inf
    )
    return torch.where(inside, result, torch.where(upper, -torch.inf, 0.0))

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    interior = (value > 0) & (value < 1)
    p = torch.where(interior, value, torch.full_like(value, 0.5))
    gumbel = -torch.log(-p.log())
    result = self.loc + self.scale * gumbel * _expm1_ratio(
        self.concentration * gumbel
    )
    safe = torch.where(
        self.concentration != 0,
        self.concentration,
        torch.ones_like(self.concentration),
    )
    endpoint = self.loc - self.scale / safe
    lower = torch.where(self.concentration > 0, endpoint, -torch.inf)
    upper = torch.where(self.concentration < 0, endpoint, torch.inf)
    return torch.where(interior, result, torch.where(value == 0, lower, upper))

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    exponential = torch.empty(
        self._extended_shape(sample_shape),
        dtype=self.loc.dtype,
        device=self.loc.device,
    ).exponential_()
    gumbel = -exponential.log()
    return self.loc + self.scale * gumbel * _expm1_ratio(
        self.concentration * gumbel
    )

SkewNormal

SkewNormal(loc, scale, skewness, validate_args=None)

Bases: Distribution

Skew-normal law in Azzalini location, scale, and skewness parameters.

PARAMETER DESCRIPTION
loc

Location of the underlying skewed normal, distinct from its mean.

TYPE: Tensor or float

scale

Positive scale, distinct from its standard deviation.

TYPE: Tensor or float

skewness

Real Azzalini shape parameter, conventionally alpha.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_skew_normal.py
def __init__(self, loc, scale, skewness, validate_args=None):
    self.loc, self.scale, self.skewness = broadcast_all(loc, scale, skewness)
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(SkewNormal, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    finite = torch.isfinite(value)
    point = torch.where(finite, value, self.loc)
    z = (point - self.loc) / self.scale
    return torch.where(
        finite, _log_density(z, self.skewness) - self.scale.log(), -torch.inf
    )

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    finite = torch.isfinite(value)
    point = torch.where(finite, value, self.loc)
    z, alpha = torch.broadcast_tensors(
        (point - self.loc) / self.scale, self.skewness
    )
    output = _SkewLogCDF.apply(z.double(), alpha.double()).to(z.dtype)
    return torch.where(finite, output, torch.where(value > 0, 0.0, -torch.inf))

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    finite = torch.isfinite(value)
    point = torch.where(finite, value, self.loc)
    z, alpha = torch.broadcast_tensors(
        (self.loc - point) / self.scale, -self.skewness
    )
    output = _SkewLogCDF.apply(z.double(), alpha.double()).to(z.dtype)
    return torch.where(finite, output, torch.where(value > 0, -torch.inf, 0.0))

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    inside = (value > 0) & (value < 1)
    p, alpha = torch.broadcast_tensors(
        torch.where(inside, value, torch.full_like(value, 0.5)), self.skewness
    )
    z = _SkewQuantile.apply(p.double(), alpha.double()).to(p.dtype)
    result = self.loc + self.scale * z
    return torch.where(
        inside, result, torch.where(value == 0, -torch.inf, torch.inf)
    )

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    shape = self._extended_shape(sample_shape)
    first = torch.randn(shape, dtype=self.loc.dtype, device=self.loc.device)
    second = torch.randn_like(first)
    denominator = torch.hypot(self.skewness, torch.ones_like(self.skewness))
    return self.loc + self.scale * (
        (self.skewness / denominator) * first.abs() + second / denominator
    )

ZeroInflatedNegativeBinomial

ZeroInflatedNegativeBinomial(zero_prob, total_count, probs, validate_args=None)

Bases: _InflatedCount

Structural zeros plus NB successes before total_count failures.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability in [0, 1].

TYPE: Tensor or float

total_count

Nonnegative negative-binomial shape.

TYPE: Tensor or float

probs

Success probability in [0, 1), with count mean r*p/(1-p).

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(self, zero_prob, total_count, probs, validate_args=None):
    self.zero_prob, self.total_count, self.probs = _broadcast_count_parameters(
        zero_prob, total_count, probs
    )
    super().__init__(self.zero_prob.shape, validate_args=validate_args)

mean property

mean: Tensor

Expected count with an exact zero-probability endpoint.

RETURNS DESCRIPTION
Tensor

Mixture probability times r*p/(1-p).

variance property

variance: Tensor

Variance in the original probability parameterization.

RETURNS DESCRIPTION
Tensor

Within-count variance plus structural-zero variation.

ZeroInflatedBinomial

ZeroInflatedBinomial(zero_prob, total_count, probs, validate_args=None)

Bases: _InflatedCount

Structural zeros plus a binomial, including zero trials.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability in [0, 1].

TYPE: Tensor or float

total_count

Nonnegative integer trial counts.

TYPE: Tensor or int

probs

Binomial success probability in [0, 1].

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(self, zero_prob, total_count, probs, validate_args=None):
    _check_trial_count_source(total_count)
    self.zero_prob, self.total_count, self.probs = _broadcast_count_parameters(
        zero_prob, total_count, probs
    )
    super().__init__(self.zero_prob.shape, validate_args=validate_args)

support

support()

Counts between zero and the trial count.

RETURNS DESCRIPTION
Constraint

The parameter-dependent integer support.

Source code in src/quivers/continuous/_zero_inflated_count.py
@constraints.dependent_property(is_discrete=True, event_dim=0)
def support(self):
    """Counts between zero and the trial count.

    Returns
    -------
    constraints.Constraint
        The parameter-dependent integer support.
    """
    return constraints.integer_interval(0, self.total_count)

ZeroInflatedBetaBinomial

ZeroInflatedBetaBinomial(zero_prob, total_count, concentration1, concentration0, validate_args=None)

Bases: ZeroInflatedBinomial

Structural zeros plus a beta-binomial with integrated success probability.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability in [0, 1].

TYPE: Tensor or float

total_count

Nonnegative integer trial counts.

TYPE: Tensor or int

concentration1

Positive beta success concentration.

TYPE: Tensor or float

concentration0

Positive beta failure concentration.

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(
    self, zero_prob, total_count, concentration1, concentration0, validate_args=None
):
    _check_trial_count_source(total_count)
    self.zero_prob, self.total_count, self.concentration1, self.concentration0 = (
        _broadcast_count_parameters(
            zero_prob, total_count, concentration1, concentration0
        )
    )
    Distribution.__init__(self, self.zero_prob.shape, validate_args=validate_args)

HurdleNegativeBinomial

HurdleNegativeBinomial(zero_prob, total_count, probs, validate_args=None)

Bases: ZeroInflatedNegativeBinomial

Zero atom plus a normalized strictly positive negative binomial.

PARAMETER DESCRIPTION
zero_prob

Hurdle probability in [0, 1].

TYPE: Tensor or float

total_count

Strictly positive negative-binomial shape.

TYPE: Tensor or float

probs

Success probability in [0, 1). At zero the positive component is its point-mass-at-one limit.

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(self, zero_prob, total_count, probs, validate_args=None):
    super().__init__(zero_prob, total_count, probs, validate_args=validate_args)

mean property

mean: Tensor

Expected hurdle count.

RETURNS DESCRIPTION
Tensor

Positive conditional mean times the nonzero probability.

variance property

variance: Tensor

Variance of the full hurdle response.

RETURNS DESCRIPTION
Tensor

Second moment minus the squared full mean.

log_prob

log_prob(value: Tensor) -> Tensor

Score the atom or normalized positive component without p=0 divisions.

PARAMETER DESCRIPTION
value

Nonnegative integer counts.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Exact log probabilities including the p=0 limit.

Source code in src/quivers/continuous/_zero_inflated_count.py
def log_prob(self, value: Tensor) -> Tensor:
    """Score the atom or normalized positive component without p=0 divisions.

    Parameters
    ----------
    value : Tensor
        Nonnegative integer counts.

    Returns
    -------
    Tensor
        Exact log probabilities including the p=0 limit.
    """
    _check_count_observation_source(value)
    if self._validate_args:
        self._validate_sample(value)
    valid = self.support.check(value)
    point = torch.where(valid & (value > 0), value, 1).to(self.probs.dtype)
    positive = (
        _log_gamma_increment(self.total_count + 1, point - 1)
        - torch.lgamma(point + 1)
        + _count_log(point - 1, self.probs)
        + self.total_count * torch.log1p(-self.probs)
        + self._positive_log_ratio()
    )
    rate = -self.total_count * torch.log1p(-self.probs)
    ordinary = rate > 1e-4
    safe_p = torch.where(ordinary, self.probs, torch.full_like(self.probs, 0.5))
    safe_r = torch.where(
        ordinary, self.total_count, torch.ones_like(self.total_count)
    )
    stable = _negative_binomial_log_mass(
        point, safe_r, safe_p.log(), torch.log1p(-safe_p)
    )
    stable = stable - torch.log(-torch.expm1(safe_r * torch.log1p(-safe_p)))
    positive = torch.where(ordinary, stable, positive)
    atom_probability = torch.where(valid & (value == 0), self.zero_prob, 1.0)
    positive_probability = torch.where(valid & (value > 0), self.zero_prob, 0.0)
    result = torch.where(
        value == 0,
        atom_probability.log(),
        torch.log1p(-positive_probability) + positive,
    )
    return torch.where(valid, result, -torch.inf)

sample

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

Draw structural zeros and efficiently conditioned positive NB counts.

PARAMETER DESCRIPTION
sample_shape

Dimensions prepended to the batch shape.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Nonnegative integer draws without reparameterized gradients.

Source code in src/quivers/continuous/_zero_inflated_count.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draw structural zeros and efficiently conditioned positive NB counts.

    Parameters
    ----------
    sample_shape : torch.Size
        Dimensions prepended to the batch shape.

    Returns
    -------
    Tensor
        Nonnegative integer draws without reparameterized gradients.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        active = torch.rand(
            shape, dtype=self.zero_prob.dtype, device=self.zero_prob.device
        ) >= self.zero_prob.expand(shape)
        result = torch.zeros(shape, dtype=torch.long, device=self.zero_prob.device)
        if active.any():
            result[active] = _positive_negative_binomial_sample(
                self.total_count.expand(shape)[active],
                self.probs.expand(shape)[active],
            )
        return result

ConditionalBernsteinHazard

ConditionalBernsteinHazard(domain, codomain, *, breaks=None, controls=None, hidden_dim=None, param_source=None, param_source_option=None)

Bases: _IndependentConditional

Learn a proportional log rate over an explicitly fixed baseline.

PARAMETER DESCRIPTION
domain

Predictor space for the log hazard multiplier.

TYPE: AnySpace

codomain

Scalar event-time coordinates, independently repeated when dim > 1.

TYPE: ContinuousSpace

breaks

Explicit retained baseline boundaries; required.

TYPE: Tensor or Sequence[float] or None DEFAULT: None

controls

Explicit normalized positive baseline coefficients; required.

TYPE: Tensor or Sequence[Sequence[float]] or None DEFAULT: None

hidden_dim

Parameter-source network widths.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Reusable source of one log rate per output coordinate.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Parameter-source strategy.

TYPE: str or None DEFAULT: None

Notes

The checked baseline is copied into fixed buffers. Knots and controls are never invented by unconstrained neural heads. Source programs can instead pass explicitly computed, differentiable controls to BernsteinHazard.

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain,
    codomain,
    *,
    breaks=None,
    controls=None,
    hidden_dim=None,
    param_source=None,
    param_source_option=None,
):
    if breaks is None or controls is None:
        raise ValueError(
            "ConditionalBernsteinHazard requires explicit fixed breaks and controls"
        )
    baseline = BernsteinHazard(breaks, controls, rate=1.0)
    if baseline.batch_shape not in (torch.Size(), torch.Size((codomain.dim,))):
        raise ValueError(
            "fixed Bernstein baseline batch must be empty or match output coordinates"
        )
    super().__init__(
        domain,
        codomain,
        BernsteinHazard,
        [("log_rate", lambda value: value)],
        hidden_dim=hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self.register_buffer("breaks", baseline.breaks.detach().clone())
    self.register_buffer("controls", baseline.controls.detach().clone())

support property

support

Return nonnegative event-time support.

RETURNS DESCRIPTION
Constraint

Nonnegative real support.

ConditionalNormal

ConditionalNormal(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source=None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional normal (Gaussian) distribution.

For each input x, produces an independent normal distribution on each dimension of the codomain:

y_i ~ Normal(mu_i(x), sigma_i(x))

Parameters are learnable: mu and log(sigma) are functions of x, implemented as lookup tables (discrete domain) or neural networks (continuous domain).

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space.

TYPE: Euclidean

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Examples:

>>> from quivers import FinSet
>>> from quivers.continuous.spaces import Euclidean
>>> A = FinSet(name="context", cardinality=5)
>>> Y = Euclidean(name="response", dim=3)
>>> f = ConditionalNormal(A, Y)
>>> x = torch.tensor([0, 1, 2])
>>> samples = f.rsample(x)  # shape (3, 3)
Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source=None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    # param_dim = d (mu) + d (log_sigma)
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d

base_dimension

base_dimension(x: Tensor) -> int

One standard-normal coordinate per independent output axis.

Source code in src/quivers/continuous/families.py
def base_dimension(self, x: torch.Tensor) -> int:
    """One standard-normal coordinate per independent output axis."""
    mu, _ = self._get_params(dimension_probe(x))
    return _event_size(mu.shape)

push_base

push_base(x: Tensor, base: Tensor) -> Tensor

The location-scale map mu(x) + sigma(x) * base.

The same map rsample applies, with the caller's coordinates in place of a fresh draw.

Source code in src/quivers/continuous/families.py
def push_base(self, x: torch.Tensor, base: torch.Tensor) -> torch.Tensor:
    """The location-scale map ``mu(x) + sigma(x) * base``.

    The same map `rsample` applies, with the caller's coordinates
    in place of a fresh draw.
    """
    mu, sigma = self._get_params(x)
    return mu + sigma * base.reshape(mu.shape)

ConditionalLogitNormal

ConditionalLogitNormal(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional logit-normal distribution on (0, 1)^d.

If z ~ Normal(mu(x), sigma(x)), then y = sigmoid(z) ~ LogitNormal. Useful for modeling probabilities and bounded quantities.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space (should have bounds [0, 1]).

TYPE: Euclidean

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d

ConditionalBeta

ConditionalBeta(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional beta distribution on (0, 1)^d.

For each input x, produces an independent Beta(alpha_i(x), beta_i(x)) on each dimension of the codomain.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space (should have bounds [0, 1]).

TYPE: Euclidean

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d

ConditionalTruncatedNormal

ConditionalTruncatedNormal(domain: AnySpace, codomain: Euclidean, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional truncated normal on [low, high]^d.

A normal distribution restricted to a bounded interval. Uses rejection-free sampling via the inverse CDF (Phi-based) method.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space (must be bounded).

TYPE: Euclidean

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: Euclidean,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    if codomain.low is None or codomain.high is None:
        raise ValueError("ConditionalTruncatedNormal requires a bounded codomain")

    super().__init__(domain, codomain)
    d = codomain.dim
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._low = codomain.low
    self._high = codomain.high

ConditionalDirichlet

ConditionalDirichlet(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional Dirichlet distribution on a probability simplex.

For each input x, produces a Dirichlet(alpha(x)) distribution on the simplex.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target simplex.

TYPE: Simplex

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self.param_source = _make_source(
        domain,
        d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d

ConditionalMultinomial

ConditionalMultinomial(domain, codomain, total_count, hidden_dim=None, param_source=None, param_source_option=None)

Bases: _ConditionalCountVector

Fixed-trial Multinomial with category logits learned from the input.

PARAMETER DESCRIPTION
domain

Input space and vector-valued output space.

TYPE: SetObject or ContinuousSpace

codomain

Input space and vector-valued output space.

TYPE: SetObject or ContinuousSpace

total_count

Nonnegative exact trials broadcastable with input batch dimensions.

TYPE: int or Tensor

hidden_dim

Parameter-network hidden dimensions.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Optional reusable category parameter source.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Parameter-source strategy.

TYPE: str or None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain,
    codomain,
    total_count,
    hidden_dim=None,
    param_source=None,
    param_source_option=None,
):
    _check_trial_count_source(total_count)
    super().__init__(domain, codomain)
    counts, _ = _count_parameters(total_count, [1.0] * codomain.dim)
    self.register_buffer("total_count", counts.to(torch.int64))
    self.param_source = _make_source(
        domain,
        codomain.dim,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalDirichletMultinomial

ConditionalDirichletMultinomial(domain, codomain, total_count, hidden_dim=None, param_source=None, param_source_option=None)

Bases: _ConditionalCountVector

Fixed-trial Dirichlet-multinomial with learned positive concentrations.

PARAMETER DESCRIPTION
domain

Input space and vector-valued output space.

TYPE: SetObject or ContinuousSpace

codomain

Input space and vector-valued output space.

TYPE: SetObject or ContinuousSpace

total_count

Nonnegative exact trials broadcastable with input batch dimensions.

TYPE: int or Tensor

hidden_dim

Parameter-network hidden dimensions.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Optional reusable category parameter source.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Parameter-source strategy.

TYPE: str or None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain,
    codomain,
    total_count,
    hidden_dim=None,
    param_source=None,
    param_source_option=None,
):
    _check_trial_count_source(total_count)
    super().__init__(domain, codomain)
    counts, _ = _count_parameters(total_count, [1.0] * codomain.dim)
    self.register_buffer("total_count", counts.to(torch.int64))
    self.param_source = _make_source(
        domain,
        codomain.dim,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalZeroInflatedBinomial

ConditionalZeroInflatedBinomial(domain, codomain, total_count, hidden_dim=None, param_source=None, param_source_option=None)

Bases: _ConditionalInflatedTrialCount

Zero-inflated binomial heads with fixed nonnegative trial counts.

PARAMETER DESCRIPTION
domain

Parameter-source domain.

TYPE: AnySpace

codomain

Independent count coordinates.

TYPE: ContinuousSpace

total_count

Fixed nonnegative number of trials.

TYPE: int

hidden_dim

Parameter-source network dimensions.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Optional reusable parameter source.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Optional source strategy.

TYPE: str or None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain,
    codomain,
    total_count,
    hidden_dim=None,
    param_source=None,
    param_source_option=None,
):
    _check_trial_count_source(total_count)
    if (
        isinstance(total_count, bool)
        or not isinstance(total_count, int)
        or total_count < 0
    ):
        raise ValueError("total_count must be a nonnegative integer")
    self._total_count = total_count
    super().__init__(
        domain,
        codomain,
        self._count_distribution,
        [
            (name, resolve_transform(transform).forward)
            for name, transform in self._count_heads
        ],
        hidden_dim,
        discrete=True,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalZeroInflatedBetaBinomial

ConditionalZeroInflatedBetaBinomial(domain, codomain, total_count, hidden_dim=None, param_source=None, param_source_option=None)

Bases: _ConditionalInflatedTrialCount

Zero-inflated beta-binomial heads with fixed nonnegative trials.

PARAMETER DESCRIPTION
domain

Parameter-source domain.

TYPE: AnySpace

codomain

Independent count coordinates.

TYPE: ContinuousSpace

total_count

Fixed nonnegative number of trials.

TYPE: int

hidden_dim

Parameter-source network dimensions.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Optional reusable parameter source.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Optional source strategy.

TYPE: str or None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain,
    codomain,
    total_count,
    hidden_dim=None,
    param_source=None,
    param_source_option=None,
):
    _check_trial_count_source(total_count)
    if (
        isinstance(total_count, bool)
        or not isinstance(total_count, int)
        or total_count < 0
    ):
        raise ValueError("total_count must be a nonnegative integer")
    self._total_count = total_count
    super().__init__(
        domain,
        codomain,
        self._count_distribution,
        [
            (name, resolve_transform(transform).forward)
            for name, transform in self._count_heads
        ],
        hidden_dim,
        discrete=True,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalUniform

ConditionalUniform(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional uniform distribution on a learnable interval.

Parameterized as Uniform(loc - width/2, loc + width/2) where loc is unconstrained and width is positive. This ensures low < high is always satisfied.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space.

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    # param_dim = d (loc) + d (raw_width)
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    # The bounds are data-dependent, so we cannot pin a single
    # interval at construction time; advertise the codomain's
    # declared bounds when available, otherwise fall back to the
    # real line.
    low, high = getattr(codomain, "low", None), getattr(codomain, "high", None)
    if low is not None and high is not None:
        self._support_cache: _constraints.Constraint = _constraints.interval(
            float(low), float(high)
        )
    else:
        self._support_cache = _constraints.real

ConditionalMultivariateNormal

ConditionalMultivariateNormal(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional multivariate normal with full covariance.

Parameterized via Cholesky factor: the parameter source outputs loc (d values) and the lower-triangular entries of L (d*(d+1)/2 values), where Sigma = L @ L^T.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space (d-dimensional).

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim - self._event_offset
    if d < 1:
        raise ValueError("Gaussian coordinate dimension must be positive")
    n_tril = d * (d + 1) // 2
    self.param_source = _make_source(
        domain,
        d + n_tril + self._extra_raw_parameters,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._n_tril = n_tril

ConditionalMultivariateStudentT

ConditionalMultivariateStudentT(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ConditionalMultivariateNormal

Learn a Student radial scale alongside the existing Gaussian heads.

PARAMETER DESCRIPTION
domain

Input carrier and real-vector response space.

TYPE: AnySpace

codomain

Input carrier and real-vector response space.

TYPE: AnySpace

hidden_dim

Parameter-network hidden dimensions.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Reusable source emitting location, packed Cholesky, and one df head.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Existing parameter-source strategy.

TYPE: str or None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim - self._event_offset
    if d < 1:
        raise ValueError("Gaussian coordinate dimension must be positive")
    n_tril = d * (d + 1) // 2
    self.param_source = _make_source(
        domain,
        d + n_tril + self._extra_raw_parameters,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._n_tril = n_tril

ConditionalAdditiveLogRatioNormal

ConditionalAdditiveLogRatioNormal(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ConditionalMultivariateNormal

Learn correlated Gaussian log ratios against the final component.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Simplex space with at least two components.

TYPE: ContinuousSpace

hidden_dim

Parameter-network hidden dimensions.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Reusable Gaussian coordinate parameter source.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Parameter-source strategy.

TYPE: str or None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim - self._event_offset
    if d < 1:
        raise ValueError("Gaussian coordinate dimension must be positive")
    n_tril = d * (d + 1) // 2
    self.param_source = _make_source(
        domain,
        d + n_tril + self._extra_raw_parameters,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._n_tril = n_tril

ConditionalLowRankMVN

ConditionalLowRankMVN(domain: AnySpace, codomain: ContinuousSpace, rank: int = 2, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional low-rank multivariate normal.

Parameterized as loc + low-rank factor + diagonal: Sigma = W @ W^T + diag(d)

This is more parameter-efficient than full MVN for high dimensions.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space (d-dimensional).

TYPE: ContinuousSpace

rank

Rank of the low-rank factor W.

TYPE: int DEFAULT: 2

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    rank: int = 2,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self._rank = rank

    # loc (d) + factor (d * rank) + diag (d)
    total = d + d * rank + d
    self.param_source = _make_source(
        domain,
        total,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalRelaxedBernoulli

ConditionalRelaxedBernoulli(domain: AnySpace, codomain: ContinuousSpace, temperature: float = 0.5, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional relaxed Bernoulli (concrete) distribution.

Outputs continuous values in (0, 1) that approximate Bernoulli samples. The temperature controls the relaxation: lower temperature = closer to discrete.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space (should be 1-d per Bernoulli component).

TYPE: ContinuousSpace

temperature

Relaxation temperature.

TYPE: float DEFAULT: 0.5

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    temperature: float = 0.5,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self.param_source = _make_source(
        domain,
        d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._temperature = temperature

ConditionalRelaxedOneHotCategorical

ConditionalRelaxedOneHotCategorical(domain: AnySpace, codomain: ContinuousSpace, temperature: float = 0.5, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional relaxed one-hot categorical (Gumbel-Softmax).

Outputs continuous vectors on the simplex that approximate one-hot categorical samples.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space (simplex or d-dimensional).

TYPE: ContinuousSpace

temperature

Relaxation temperature.

TYPE: float DEFAULT: 0.5

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    temperature: float = 0.5,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self.param_source = _make_source(
        domain,
        d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._temperature = temperature

ConditionalWishart

ConditionalWishart(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional Wishart distribution over positive-definite matrices.

Produces random d x d positive-definite matrices. Parameterized by degrees of freedom df(x) and a scale matrix V(x).

The codomain dimension is interpreted as d, and outputs are d x d matrices flattened to d^2.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space. dim is the matrix size d (output is d x d).

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    n_tril = d * (d + 1) // 2
    # df (1) + lower-triangular scale (n_tril)
    self.param_source = _make_source(
        domain,
        1 + n_tril,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._n_tril = n_tril

ConditionalMatrixNormal

ConditionalMatrixNormal(domain: AnySpace, codomain: ContinuousSpace, rows: int, cols: int, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional Matrix-Normal :math:\mathcal{MN}(M, U, V).

The matrix-Normal distribution on :math:\mathbb{R}^{n \times p} factorises with a Kronecker-product covariance: if :math:X \sim \mathcal{MN}(M, U, V) then :math:\mathrm{vec}(X) \sim \mathcal{N}(\mathrm{vec}(M), V \otimes U) with :math:U \in \mathbb{R}^{n \times n} the row covariance and :math:V \in \mathbb{R}^{p \times p} the column covariance.

Categorically, the Kronecker structure is the tensor product of two Gaussians; it is strictly more constrained than the flat :math:np-dim MVN that the same parameter tensor could carry, so the surface keeps the two families distinct (no auto-substitution). Use this when the prior should express independent row and column correlation structure.

The codomain's product factorisation supplies the row and column dimensions. The grammar surface ~ MatrixNormal(loc, row_scale, col_scale) over (dom, cod) binds the first axis listed in over to the row covariance and the second to the column covariance.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: AnySpace

codomain

Target space whose factorisation supplies (n, p). Must carry a product structure of two factors; the first is the row axis, the second the column.

TYPE: ContinuousSpace

rows

Row dimension :math:n.

TYPE: int

cols

Column dimension :math:p.

TYPE: int

hidden_dim

Hidden layer width for the parameter network.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    rows: int,
    cols: int,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    self._rows = int(rows)
    self._cols = int(cols)
    n_loc = self._rows * self._cols
    n_row_tril = self._rows * (self._rows + 1) // 2
    n_col_tril = self._cols * (self._cols + 1) // 2
    self._n_loc = n_loc
    self._n_row_tril = n_row_tril
    self._n_col_tril = n_col_tril
    self.param_source = _make_source(
        domain,
        n_loc + n_row_tril + n_col_tril,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

The log density of a matrix at an input.

PARAMETER DESCRIPTION
x

The input.

TYPE: Tensor

y

The matrix, (..., n, p) or flattened row-major (..., n * p).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The log densities.

Source code in src/quivers/continuous/families.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """The log density of a matrix at an input.

    Parameters
    ----------
    x : torch.Tensor
        The input.
    y : torch.Tensor
        The matrix, ``(..., n, p)`` or flattened row-major
        ``(..., n * p)``.

    Returns
    -------
    torch.Tensor
        The log densities.
    """
    if y.dim() < 2 or y.shape[-2:] != (self._rows, self._cols):
        y = y.reshape(*y.shape[:-1], self._rows, self._cols)
    return self._get_dist(x).log_prob(y)

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Draw a matrix at an input.

PARAMETER DESCRIPTION
x

The input.

TYPE: Tensor

sample_shape

Leading sample axes.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

The draws, (*sample_shape, ..., n, p).

Source code in src/quivers/continuous/families.py
def rsample(
    self,
    x: torch.Tensor,
    sample_shape: torch.Size = torch.Size(),
) -> torch.Tensor:
    """Draw a matrix at an input.

    Parameters
    ----------
    x : torch.Tensor
        The input.
    sample_shape : torch.Size
        Leading sample axes.

    Returns
    -------
    torch.Tensor
        The draws, ``(*sample_shape, ..., n, p)``.
    """
    return self._get_dist(x).rsample(sample_shape)

ConditionalInverseWishart

ConditionalInverseWishart(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional Inverse-Wishart over positive-definite matrices.

Conjugate prior for the covariance of a multivariate normal. Realised as a deterministic inversion of a Wishart sample so autograd flows; equivalent in distribution to drawing :math:\Sigma^{-1} \sim \mathcal{W}(\nu, V^{-1}) and inverting. See Gelman et al. (2013) §3.6 for the conjugacy statement.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: AnySpace

codomain

Target space whose dim is the matrix size :math:d.

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for the parameter network.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    n_tril = d * (d + 1) // 2
    self._d = d
    self._n_tril = n_tril
    self.param_source = _make_source(
        domain,
        1 + n_tril,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

The log density of a matrix at an input.

PARAMETER DESCRIPTION
x

The input.

TYPE: Tensor

y

The matrix, (..., d, d) or flattened (..., d * d).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The log densities.

Source code in src/quivers/continuous/families.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """The log density of a matrix at an input.

    Parameters
    ----------
    x : torch.Tensor
        The input.
    y : torch.Tensor
        The matrix, ``(..., d, d)`` or flattened ``(..., d * d)``.

    Returns
    -------
    torch.Tensor
        The log densities.
    """
    d = self._d
    if y.dim() < 2 or y.shape[-2:] != (d, d):
        y = y.reshape(*y.shape[:-1], d, d)
    return self._get_dist(x).log_prob(y)

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Draw a matrix at an input.

PARAMETER DESCRIPTION
x

The input.

TYPE: Tensor

sample_shape

Leading sample axes.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

The draws, flattened row-major to (..., d * d).

Source code in src/quivers/continuous/families.py
def rsample(
    self,
    x: torch.Tensor,
    sample_shape: torch.Size = torch.Size(),
) -> torch.Tensor:
    """Draw a matrix at an input.

    Parameters
    ----------
    x : torch.Tensor
        The input.
    sample_shape : torch.Size
        Leading sample axes.

    Returns
    -------
    torch.Tensor
        The draws, flattened row-major to ``(..., d * d)``.
    """
    sigma = self._get_dist(x).rsample(sample_shape)
    return sigma.reshape(*sigma.shape[:-2], self._d * self._d)

ConditionalBernoulli

ConditionalBernoulli(domain: AnySpace, codomain: AnySpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional Bernoulli: continuous probability -> discrete truth value.

Takes a continuous input x and produces learnable logits that parameterize a Bernoulli distribution. The output is a discrete sample in {0, 1}, returned as a LongTensor.

This is the key bridge used in PDS (Grove & White) for the Bern x pattern, where a LogitNormal draw x in (0,1) parameterizes a Bernoulli over truth values.

The codomain must be a FinSet of size 2 (representing {False, True} or {0, 1}).

Note

Sampling from Bernoulli is NOT reparameterizable. Gradients do not flow through the discrete samples. Use score function estimators (REINFORCE) or the Gumbel-Softmax trick if differentiable samples are needed.

PARAMETER DESCRIPTION
domain

Source space (typically UnitInterval or a FinSet).

TYPE: SetObject or ContinuousSpace

codomain

Target FinSet of size 2.

TYPE: SetObject

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: AnySpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    if not isinstance(codomain, SetObject) or codomain.size != 2:
        raise ValueError(
            f"ConditionalBernoulli requires a FinSet(2) codomain, got {codomain!r}"
        )

    super().__init__(domain, codomain)

    # one logit per input
    self.param_source = _make_source(
        domain,
        1,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

Log-probability of discrete output y given input x.

PARAMETER DESCRIPTION
x

Input tensor.

TYPE: Tensor

y

Discrete output in {0, 1}. Shape (batch,).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log-probabilities. Shape (batch,).

Source code in src/quivers/continuous/families.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """Log-probability of discrete output y given input x.

    Parameters
    ----------
    x : torch.Tensor
        Input tensor.
    y : torch.Tensor
        Discrete output in {0, 1}. Shape (batch,).

    Returns
    -------
    torch.Tensor
        Log-probabilities. Shape (batch,).
    """
    probs = self._get_probs(x)
    dist = D.Bernoulli(probs=probs)
    return dist.log_prob(y.float())

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Sample from Bernoulli (not reparameterizable).

PARAMETER DESCRIPTION
x

Input tensor.

TYPE: Tensor

sample_shape

Additional leading sample dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Discrete samples in {0, 1}. Shape (*sample_shape, batch).

Source code in src/quivers/continuous/families.py
def rsample(
    self,
    x: torch.Tensor,
    sample_shape: torch.Size = torch.Size(),
) -> torch.Tensor:
    """Sample from Bernoulli (not reparameterizable).

    Parameters
    ----------
    x : torch.Tensor
        Input tensor.
    sample_shape : torch.Size
        Additional leading sample dimensions.

    Returns
    -------
    torch.Tensor
        Discrete samples in {0, 1}. Shape (*sample_shape, batch).
    """
    probs = self._get_probs(x)
    dist = D.Bernoulli(probs=probs)
    return dist.sample(sample_shape).long()

ConditionalCategorical

ConditionalCategorical(domain: AnySpace, codomain: AnySpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional Categorical: continuous input -> discrete category.

Generalizes ConditionalBernoulli to k > 2 categories. Takes a continuous input and produces learnable logits over k categories. The output is a discrete sample in {0, ..., k-1}.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target FinSet of size k.

TYPE: SetObject

hidden_dim

Hidden layer width for neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: AnySpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    if not isinstance(codomain, SetObject):
        raise ValueError(
            f"ConditionalCategorical requires a FinSet codomain, got {codomain!r}"
        )

    super().__init__(domain, codomain)
    self._k = codomain.size
    self.param_source = _make_source(
        domain,
        self._k,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

support property

support

Discrete-integer support over {0, …, k-1}.

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

Log-probability of discrete output y given input x.

PARAMETER DESCRIPTION
x

Input tensor.

TYPE: Tensor

y

Discrete output in {0, ..., k-1}. Shape (batch,).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log-probabilities. Shape (batch,).

Source code in src/quivers/continuous/families.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """Log-probability of discrete output y given input x.

    Parameters
    ----------
    x : torch.Tensor
        Input tensor.
    y : torch.Tensor
        Discrete output in {0, ..., k-1}. Shape (batch,).

    Returns
    -------
    torch.Tensor
        Log-probabilities. Shape (batch,).
    """
    logits = self._get_logits(x)
    dist = D.Categorical(logits=logits)
    return dist.log_prob(y.long())

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Sample from Categorical (not reparameterizable).

PARAMETER DESCRIPTION
x

Input tensor.

TYPE: Tensor

sample_shape

Additional leading sample dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Discrete samples in {0, ..., k-1}. Shape (*sample_shape, batch).

Source code in src/quivers/continuous/families.py
def rsample(
    self,
    x: torch.Tensor,
    sample_shape: torch.Size = torch.Size(),
) -> torch.Tensor:
    """Sample from Categorical (not reparameterizable).

    Parameters
    ----------
    x : torch.Tensor
        Input tensor.
    sample_shape : torch.Size
        Additional leading sample dimensions.

    Returns
    -------
    torch.Tensor
        Discrete samples in {0, ..., k-1}. Shape (*sample_shape, batch).
    """
    logits = self._get_logits(x)
    dist = D.Categorical(logits=logits)
    return dist.sample(sample_shape).long()

ConditionalBinomial

ConditionalBinomial(domain: AnySpace, codomain: ContinuousSpace, total_count: int = 1, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional Binomial(total_count, probs(x)).

The total_count (number of trials) is a fixed hyperparameter set at construction time, typical for binomial likelihoods where n is known per observation. Only the probs parameter is learnable.

Outputs integer counts in {0, 1, ..., total_count}.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space.

TYPE: ContinuousSpace

total_count

Number of Bernoulli trials per observation.

TYPE: int DEFAULT: 1

hidden_dim

Hidden layer width for the parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    total_count: int = 1,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    _check_trial_count_source(total_count)
    if (
        isinstance(total_count, bool)
        or not isinstance(total_count, int)
        or total_count < 0
    ):
        raise ValueError(
            f"ConditionalBinomial: total_count must be a nonnegative integer, got {total_count}"
        )
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self._total_count = int(total_count)
    self.param_source = _make_source(
        domain,
        d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalLogisticNormal

ConditionalLogisticNormal(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional LogisticNormal on the simplex.

Pushes a Normal(loc(x), scale(x)) draw through the softmax transform to produce a simplex-valued sample. Multivariate analogue of ConditionalLogitNormal. Useful as an alternative to ConditionalDirichlet when the underlying simplex distribution should be Gaussian in logit space rather than Beta-shaped.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space; codomain.dim is the simplex dimension.

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for the parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    # We use a Normal in (d-1)-dim space and the
    # StickBreakingTransform to land on the d-simplex.
    # torch.distributions.LogisticNormal handles this.
    self.param_source = _make_source(
        domain,
        2 * (d - 1),
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d

ConditionalZeroInflatedPoisson

ConditionalZeroInflatedPoisson(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional ZeroInflatedPoisson(zero_prob(x), rate(x)).

The parameter source produces 2 * codomain.dim numbers per input row: the first half feeds a sigmoid to produce the zero-inflation probability, the second half a softplus to produce the Poisson rate. Outputs non-negative integer counts.

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalHurdlePoisson

ConditionalHurdlePoisson(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional HurdlePoisson(zero_prob(x), rate(x)).

Same parameter shape as ConditionalZeroInflatedPoisson but the two-stage hurdle log-density: a Bernoulli for zero vs positive, then a zero-truncated Poisson for the strictly-positive branch.

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalZeroOneInflatedBeta

ConditionalZeroOneInflatedBeta(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional ZeroOneInflatedBeta(mu(x), phi(x), zoi(x), coi(x)).

Parameter source emits 4 * dim numbers per row: logit-mu, log-phi, logit-zoi, logit-coi. Used by the runtime family registry for ~ ZeroOneInflatedBeta declarations; formula frontend prefers the inline observe ... <- ZeroOneInflatedBeta(mu, phi, zoi, coi).

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self.param_source = _make_source(
        domain,
        4 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalMixtureNormal

ConditionalMixtureNormal(domain: AnySpace, codomain: ContinuousSpace, num_components: int = 2, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional finite Gaussian mixture with input-driven weights, locations, and scales.

The parameter source produces 3 * K numbers per row, where K is the number of mixture components (fixed at construction). Weights pass through softmax, locations are emitted directly, scales pass through softplus + epsilon.

The codomain is assumed scalar (1-d real); a higher-dimensional extension would replace Normal with Independent(Normal(...), 1) and triple the per-component parameter count.

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    num_components: int = 2,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    if num_components < 2:
        raise ValueError(
            "ConditionalMixtureNormal: num_components must be >= 2, "
            f"got {num_components}"
        )
    super().__init__(domain, codomain)
    self._k = int(num_components)
    self.param_source = _make_source(
        domain,
        3 * self._k,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalOneHotCategorical

ConditionalOneHotCategorical(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional OneHotCategorical(probs(x)).

Generalises ConditionalCategorical to one-hot encoded outputs (vector of zeros with a single one). Useful as a discrete-output observation kernel where downstream code wants a vector rather than an integer index.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space; codomain.dim is the number of categories.

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for the parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self.param_source = _make_source(
        domain,
        d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalMixture

ConditionalMixture(domain: AnySpace, codomain: ContinuousSpace, component_class: type, num_components: int = 4, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

K-component mixture of a conditional family.

Wraps a single conditional family class (one of the registered ConditionalX types) and gives it K independent parameterizations plus learnable mixture logits, producing

p(y | x) = sum_k pi_k(x) * f_k(y | x)

where each f_k is an instance of the component class and pi is the softmax of K learnable logits.

Sampling is via ancestral simulation (Categorical pick + the chosen component's rsample). log_prob evaluates the log-sum-exp of the per-component log-densities. The Categorical pick is non-reparameterizable; gradient flow through the weights uses the score-function path (which higher-level objectives like IWAE can route through).

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space; matches the component family's codomain.

TYPE: ContinuousSpace

component_class

A ConditionalX class accepting (domain, codomain, hidden_dim) constructor args.

TYPE: type

num_components

Number of mixture components.

TYPE: int DEFAULT: 4

hidden_dim

Hidden width for both the mixture-logit MLP and each component's parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    component_class: type,
    num_components: int = 4,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    if num_components < 2:
        raise ValueError(
            f"ConditionalMixture: num_components must be >= 2, got {num_components}"
        )
    super().__init__(domain, codomain)
    self._K = int(num_components)
    self._components = torch.nn.ModuleList(
        [component_class(domain, codomain, hidden_dim) for _ in range(self._K)]
    )
    self.mixture_logits = _make_source(
        domain,
        self._K,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalIndependent

ConditionalIndependent(base: ContinuousMorphism)

Bases: ContinuousMorphism

Reinterpret the trailing batch dimension of a base conditional family as an event dimension.

Equivalent to wrapping the base distribution in torch.distributions.Independent with reinterpreted_batch_ndims = 1. Used to make per-element independence explicit when a downstream guide wants to score a vector-valued observation as a single event.

PARAMETER DESCRIPTION
base

The base conditional family. The wrapped distribution sums the base's per-element log-probabilities along the last axis to score a vector-valued observation.

TYPE: ContinuousMorphism

Source code in src/quivers/continuous/families.py
def __init__(self, base: ContinuousMorphism) -> None:
    super().__init__(base.domain, base.codomain)
    self._base = base

ConditionalTransformed

ConditionalTransformed(base: ContinuousMorphism, transforms: list)

Bases: ContinuousMorphism

A base conditional family composed with a chain of bijectors.

Equivalent to torch.distributions.TransformedDistribution lifted to ContinuousMorphism. The transforms are applied in forward order to rsample outputs; log_prob includes the log-determinant Jacobian correction.

PARAMETER DESCRIPTION
base

Base conditional family.

TYPE: ContinuousMorphism

transforms

Bijectors applied in forward order. Each must implement __call__, inv, and log_abs_det_jacobian.

TYPE: list of torch.distributions.Transform

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    base: ContinuousMorphism,
    transforms: list,
) -> None:
    super().__init__(base.domain, base.codomain)
    self._base = base
    self._transforms = list(transforms)

ConditionalLKJCholesky

ConditionalLKJCholesky(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional LKJCholesky(dim, concentration(x)).

Produces lower-triangular Cholesky factors of correlation matrices on the LKJ distribution (Lewandowski-Kurowicka-Joe 2009, doi:10.1016/j.jmva.2009.04.008). The matrix dimension is taken from codomain.dim; only the concentration parameter is learnable. Draws use the onion method of that paper (section 3.2), the construction the QIEC reference machine also draws by, so every off-diagonal correlation r in dimension d has (r + 1) / 2 ~ Beta(eta - 1 + d / 2, eta - 1 + d / 2).

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space; codomain.dim is the correlation-matrix size.

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for the parameter source.

TYPE: int DEFAULT: None

param_source

A prebuilt source of the concentration's raw value.

TYPE: ParamSource or None DEFAULT: None

param_source_option

The named parameter-source kind to build.

TYPE: str or None DEFAULT: None

RAISES DESCRIPTION
TypeError

If codomain.dim is not an integer.

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    matrix_dim = codomain.dim
    if not isinstance(matrix_dim, int):
        raise TypeError(
            "ConditionalLKJCholesky needs a codomain with an integer "
            f"dimension, got {matrix_dim!r}"
        )
    self._matrix_dim = matrix_dim
    self.param_source = _make_source(
        domain,
        1,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Draw one Cholesky factor per input row, by the onion method.

The factors are differentiable in the concentration, and so in the parameter source, through implicitly reparameterized Beta draws.

PARAMETER DESCRIPTION
x

The input the concentration is computed from.

TYPE: Tensor

sample_shape

Leading sample dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Factors of shape (*sample_shape, batch, dim, dim).

Source code in src/quivers/continuous/families.py
def rsample(
    self,
    x: torch.Tensor,
    sample_shape: torch.Size = torch.Size(),
) -> torch.Tensor:
    """Draw one Cholesky factor per input row, by the onion method.

    The factors are differentiable in the concentration, and so in the
    parameter source, through implicitly reparameterized Beta draws.

    Parameters
    ----------
    x : torch.Tensor
        The input the concentration is computed from.
    sample_shape : torch.Size
        Leading sample dimensions.

    Returns
    -------
    torch.Tensor
        Factors of shape ``(*sample_shape, batch, dim, dim)``.
    """
    dist = self._get_dist(x)
    return dist.rsample(sample_shape)

ConditionalGaussianProcess

ConditionalGaussianProcess(domain: AnySpace, codomain: ContinuousSpace, kernel: str = 'rbf', length_scale: float = 1.0, amplitude: float = 1.0, jitter: float = 1e-06)

Bases: ContinuousMorphism

Gaussian process prior with mean zero and a chosen covariance kernel.

A Gaussian process is a Markov kernel X^N -> G(R^N) whose value at a finite set of input locations x_1, ..., x_N follows a multivariate Normal with covariance matrix K(x_i, x_j). Unlike the parametric families that derive their distribution parameters from a neural network on the input, the GP's "parameters" are the input locations themselves: the kernel function evaluated on the inputs produces the covariance directly.

Reference: Rasmussen & Williams (2006), Gaussian Processes for Machine Learning.

PARAMETER DESCRIPTION
domain

Source space. Its dim is the per-location feature dimensionality D of the inputs.

TYPE: SetObject or ContinuousSpace

codomain

Target space. Its dim is the number of input locations N at which the GP is evaluated.

TYPE: ContinuousSpace

kernel

Covariance kernel. "rbf" is the squared-exponential kernel; "matern52" is the Matern kernel with smoothness nu = 5/2; "linear" is the inner-product kernel.

TYPE: ('rbf', 'matern52', 'linear') DEFAULT: "rbf"

length_scale

Initial length scale of the kernel (positive; learnable). Ignored by the linear kernel.

TYPE: float DEFAULT: 1.0

amplitude

Initial amplitude (positive; learnable). Multiplies the kernel by amplitude^2.

TYPE: float DEFAULT: 1.0

jitter

Diagonal regulariser added to K for numerical positive-definiteness of the Cholesky factorisation.

TYPE: float DEFAULT: 1e-06

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    kernel: str = "rbf",
    length_scale: float = 1.0,
    amplitude: float = 1.0,
    jitter: float = 1e-6,
) -> None:
    super().__init__(domain, codomain)
    if kernel not in _GP_KERNEL_CHOICES:
        raise ValueError(
            f"ConditionalGaussianProcess: unknown kernel {kernel!r}; "
            f"valid choices: {_GP_KERNEL_CHOICES}"
        )
    if length_scale <= 0.0:
        raise ValueError(
            f"ConditionalGaussianProcess: length_scale must be > 0, got {length_scale!r}"
        )
    if amplitude <= 0.0:
        raise ValueError(
            f"ConditionalGaussianProcess: amplitude must be > 0, got {amplitude!r}"
        )
    self._kernel = kernel
    self._jitter = jitter
    self._n = codomain.dim
    self._d = getattr(domain, "dim", None)
    # Store raw (pre-softplus) parameters so the transformed value
    # is strictly positive and the optimiser sees unconstrained
    # variables.
    inv_softplus_ls = math.log(math.expm1(length_scale))
    inv_softplus_amp = math.log(math.expm1(amplitude))
    self._raw_length_scale = torch.nn.Parameter(
        torch.tensor(inv_softplus_ls, dtype=torch.get_default_dtype())
    )
    self._raw_amplitude = torch.nn.Parameter(
        torch.tensor(inv_softplus_amp, dtype=torch.get_default_dtype())
    )

length_scale property

length_scale: Tensor

Current (positive) length scale of the kernel.

amplitude property

amplitude: Tensor

Current (positive) amplitude of the kernel.

ConditionalHorseshoe

ConditionalHorseshoe(domain: AnySpace, codomain: ContinuousSpace, scale: float = 1.0)

Bases: ContinuousMorphism

Carvalho-Polson-Scott horseshoe prior.

The horseshoe prior places a global-local shrinkage structure on each coordinate:

.. code-block:: text

tau = scale positive learnable global parameter lambda_d ~ HalfCauchy(1) for d = 1, ..., D beta_d | tau, lambda_d ~ Normal(0, tau * lambda_d)

The global scale is a module parameter; it is not a sampled hyperprior. Formula RegularizedHorseshoe priors instead emit explicit global, local, and slab latent sites. The marginal density of beta_d after integrating the local scale lambda_d has no closed form; this implementation uses a 16-point Gauss-Legendre quadrature after mapping the half-line lambda in (0, inf) to t in (0, 1) via the change of variables lambda = tan(pi * t / 2), whose Jacobian is (pi / 2) * sec^2(pi * t / 2).

Reference: Carvalho, Polson & Scott (2010), The horseshoe estimator for sparse signals.

PARAMETER DESCRIPTION
domain

Source space. The prior is conditionally independent of x; x only carries the batch shape.

TYPE: SetObject or ContinuousSpace

codomain

Target space. Its dim is the coordinate count D.

TYPE: ContinuousSpace

scale

Initial global shrinkage tau (positive; learnable).

TYPE: float DEFAULT: 1.0

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    scale: float = 1.0,
) -> None:
    super().__init__(domain, codomain)
    if scale <= 0.0:
        raise ValueError(f"ConditionalHorseshoe: scale must be > 0, got {scale!r}")
    self._d = codomain.dim
    inv_softplus_scale = math.log(math.expm1(scale))
    self._raw_scale = torch.nn.Parameter(
        torch.tensor(inv_softplus_scale, dtype=torch.get_default_dtype())
    )

scale property

scale: Tensor

Current (positive) global shrinkage tau.

ConditionalLearnedOrderedLogistic

ConditionalLearnedOrderedLogistic(domain: AnySpace, codomain: AnySpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional OrderedLogistic(predictor(x), cutpoints(x)), cutpoints learned.

This is the morphism a ~ OrderedLogistic declaration compiles to. ConditionalOrderedLogistic is the variant that takes its cutpoints explicitly.

The continuous input drives a parameter source that produces 1 + (K - 1) numbers: one real predictor and a K - 1 cutpoint vector. The cutpoints are passed through a strictly-monotonic transform (first entry free, subsequent entries via cumulative softplus) so the cumulative-link contract c_0 < c_1 < ... < c_{K-2} is satisfied unconditionally.

Outputs integer categories in {0, ..., K - 1} where K = codomain.size.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: AnySpace

codomain

A finite set of at least two ordered categories.

TYPE: AnySpace

hidden_dim

Hidden widths, read only by a source that has hidden layers.

TYPE: int or sequence of int DEFAULT: None

param_source

Select the parameter source directly, or by the DSL's [param_source=...] text.

TYPE: ParamSource | None DEFAULT: None

param_source_option

Select the parameter source directly, or by the DSL's [param_source=...] text.

TYPE: ParamSource | None DEFAULT: None

RAISES DESCRIPTION
ValueError

If the codomain is not a finite set of at least two categories.

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: AnySpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    if not isinstance(codomain, SetObject):
        raise ValueError(
            "ConditionalLearnedOrderedLogistic requires a FinSet codomain, "
            f"got {codomain!r}"
        )
    if codomain.size < 2:
        raise ValueError(
            "ConditionalLearnedOrderedLogistic requires K >= 2 categories, "
            f"got codomain.size = {codomain.size}"
        )
    super().__init__(domain, codomain)
    self._k = codomain.size
    self.param_source = _make_source(
        domain,
        1 + (self._k - 1),
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalGeneralizedPareto

ConditionalGeneralizedPareto(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional generalized Pareto distribution.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space.

TYPE: ContinuousSpace

hidden_dim

Hidden widths, read only by a source that has hidden layers.

TYPE: int or sequence of int DEFAULT: None

param_source

Select the parameter source directly, or by the DSL's [param_source=...] text.

TYPE: ParamSource | None DEFAULT: None

param_source_option

Select the parameter source directly, or by the DSL's [param_source=...] text.

TYPE: ParamSource | None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    # loc + scale + concentration
    self.param_source = _make_source(
        domain,
        3 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d

ConditionalBetaBinomial

ConditionalBetaBinomial(domain: AnySpace, codomain: ContinuousSpace, total_count: int, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conjugate Beta-Binomial likelihood with learnable Beta parameters.

The number of successes y arises by drawing p ~ Beta(concentration1(x), concentration0(x)) and then y ~ Binomial(total_count, p). The Beta is integrated out analytically, yielding the log-probability

.. math::

\log p(y \mid x) = \log \Gamma(\alpha + \beta)
    + \log \Gamma(\alpha + y) + \log \Gamma(\beta + n - y)
    - \log \Gamma(\alpha) - \log \Gamma(\beta)
    - \log \Gamma(\alpha + \beta + n)
    + \log \binom{n}{y}

where :math:\alpha = \mathrm{concentration1}(x), :math:\beta = \mathrm{concentration0}(x), and :math:n is total_count.

Sampling is not reparameterisable; rsample raises and sample draws p from the Beta and y from the resulting Binomial.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space. codomain.dim independent Beta-Binomial observations are produced per input.

TYPE: ContinuousSpace

total_count

Number of Bernoulli trials per observation; must be a nonnegative integer.

TYPE: int

hidden_dim

Hidden layer width for the neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    total_count: int,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    _check_trial_count_source(total_count)
    if (
        isinstance(total_count, bool)
        or not isinstance(total_count, int)
        or total_count < 0
    ):
        raise ValueError(
            f"ConditionalBetaBinomial: total_count must be a nonnegative integer, got {total_count}"
        )
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self._total_count = int(total_count)
    # Two raw scalars per codomain dim: alpha and beta concentrations.
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalLogistic

ConditionalLogistic(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional logistic distribution on the real line.

Independent per codomain dim with learnable location and scale:

.. math::

\log p(y \mid x) = -z - 2 \log(1 + e^{-z}) - \log \sigma

where :math:z = (y - \mu) / \sigma. Samples are reparameterised via the inverse-CDF transform of a uniform draw, :math:y = \mu + \sigma \log(u / (1 - u)).

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space. codomain.dim independent logistic components are produced per input.

TYPE: ContinuousSpace

hidden_dim

Hidden layer width for the neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    # param_dim = d (loc) + d (raw_scale).
    self.param_source = _make_source(
        domain,
        2 * d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

ConditionalHalfStudentT

ConditionalHalfStudentT(domain: AnySpace, codomain: ContinuousSpace, df: float, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ContinuousMorphism

Conditional half-StudentT on the positive reals.

A StudentT with df fixed at construction time, learnable scale, and location fixed at zero, restricted to nonnegative values via reflection. The folded log-density at y >= 0 is log 2 + log_prob_studentt(0, scale(x), df; y) and -inf elsewhere.

Sampling reflects a base StudentT draw through the origin: y = |z| with z ~ StudentT(df, 0, scale). Reparameterisation flows through the absolute-value operation.

PARAMETER DESCRIPTION
domain

Source space.

TYPE: SetObject or ContinuousSpace

codomain

Target space. codomain.dim independent half-StudentT components are produced per input.

TYPE: ContinuousSpace

df

Degrees-of-freedom hyperparameter (positive). Held fixed across observations; only scale is learnable.

TYPE: float

hidden_dim

Hidden layer width for the neural parameter source.

TYPE: int DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    df: float,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    if df <= 0.0:
        raise ValueError(f"ConditionalHalfStudentT: df must be > 0, got {df!r}")
    super().__init__(domain, codomain)
    d = codomain.dim
    self._d = d
    self._df = float(df)
    self.param_source = _make_source(
        domain,
        d,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )

LKJCorrelationFactor

LKJCorrelationFactor(dim: int, eta: float, domain: AnySpace)

Bases: ContinuousMorphism

LKJ prior on Cholesky factors LKJ(K, η) over CholeskyFactor(K).

Density on the Cholesky factor:

.. math::

p(L) \propto \prod_{k=2}^{K} L_{kk}^{K - k + 2(\eta - 1)}.

A higher concentration :math:\eta > 1 pulls toward the identity correlation; :math:\eta = 1 is uniform on correlations. Sampling uses the onion method of Lewandowski-Kurowicka-Joe 2009 (section 3.2, doi:10.1016/j.jmva.2009.04.008): row :math:k (zero-based) of :math:L is :math:(\sqrt{y}\, u, \sqrt{1 - y}) for :math:y \sim \mathrm{Beta}(k/2, \eta + (K - 1 - k)/2) and :math:u uniform on the unit sphere in :math:\mathbb{R}^k. The construction is shared with the QIEC reference machine, and the draws are differentiable in :math:\eta.

PARAMETER DESCRIPTION
dim

Correlation-matrix size :math:K \ge 2.

TYPE: int

eta

Concentration :math:\eta > 0.

TYPE: float

domain

The morphism's source (parameter conditioning); typically the program's input space. The LKJ prior itself does not consume per-observation conditioning, so the rsample path broadcasts the prior across the batch dimension.

TYPE: AnySpace

Source code in src/quivers/continuous/families.py
def __init__(self, dim: int, eta: float, domain: AnySpace) -> None:
    if dim < 2:
        raise ValueError(f"LKJ requires dim >= 2; got {dim}")
    if eta <= 0:
        raise ValueError(f"LKJ requires eta > 0; got {eta}")
    codomain = CholeskyFactor(name=f"L({dim})", dim=dim)
    super().__init__(domain, codomain)
    self._dim = dim
    self._eta = float(eta)

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Draw one Cholesky factor per input row, by the onion method.

PARAMETER DESCRIPTION
x

The input; only its row count, device, and dtype are read.

TYPE: Tensor

sample_shape

Leading sample dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Flat factors, shape (*sample_shape, batch, dim * dim).

Source code in src/quivers/continuous/families.py
def rsample(
    self, x: torch.Tensor, sample_shape: torch.Size = torch.Size()
) -> torch.Tensor:
    """Draw one Cholesky factor per input row, by the onion method.

    Parameters
    ----------
    x : torch.Tensor
        The input; only its row count, device, and dtype are read.
    sample_shape : torch.Size
        Leading sample dimensions.

    Returns
    -------
    torch.Tensor
        Flat factors, shape ``(*sample_shape, batch, dim * dim)``.
    """
    batch = x.shape[0]
    factors = self._distribution(x).rsample(torch.Size(sample_shape) + (batch,))
    return factors.reshape(*factors.shape[:-2], self._dim * self._dim)

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

Normalized log density of the LKJ prior at Cholesky factors.

PARAMETER DESCRIPTION
x

The input; it carries no parameters.

TYPE: Tensor

y

Factors, flat (..., dim * dim) or square (..., dim, dim).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One log density per factor.

Source code in src/quivers/continuous/families.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """Normalized log density of the LKJ prior at Cholesky factors.

    Parameters
    ----------
    x : torch.Tensor
        The input; it carries no parameters.
    y : torch.Tensor
        Factors, flat ``(..., dim * dim)`` or square
        ``(..., dim, dim)``.

    Returns
    -------
    torch.Tensor
        One log density per factor.
    """
    K = self._dim
    if y.shape[-2:] != (K, K):
        y = y.reshape(*y.shape[:-1], K, K)
    return self._distribution(x).log_prob(y)

Truncated

Truncated(base: ContinuousMorphism, lower: float | None = None, upper: float | None = None, max_rejection_iterations: int = 64)

Bases: ContinuousMorphism

Truncate a base family to an interval :math:[a, b].

Categorical denotation: given a base family :math:F : \Theta \to \mathcal{G}(\mathbb{R}) and constants :math:a, b \in \bar{\mathbb{R}} with :math:a < b, the truncated family has density

.. math::

p_{F_{|[a,b]}}(x) = \frac{p_F(x)}{F_{\text{cdf}}(b)
- F_{\text{cdf}}(a)} \cdot \mathbb{1}_{[a,b]}(x)

and the morphism :math:F_{|[a,b]} : \Theta \to \mathcal{G}([a,b]). Independent output coordinates are conditioned separately; coupled events require a joint rectangle probability and are rejected. Normalizing masses are deterministic and retain parameter gradients supported by the base CDF. Normal sampling uses a log-space inverse CDF; other bases use bounded rejection.

PARAMETER DESCRIPTION
base

The base distribution-family morphism. Must expose log_prob and rsample plus _get_dist(x) returning the scalar-coordinate distributions. The base must supply an analytic CDF or stable log-tail methods for normalization.

TYPE: ContinuousMorphism

lower

Lower bound :math:a. None means :math:-\infty.

TYPE: float or None DEFAULT: None

upper

Upper bound :math:b. None means :math:+\infty.

TYPE: float or None DEFAULT: None

max_rejection_iterations

Cap on rejection-sampling attempts before raising.

TYPE: int DEFAULT: 64

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    base: ContinuousMorphism,
    lower: float | None = None,
    upper: float | None = None,
    max_rejection_iterations: int = 64,
) -> None:
    super().__init__(base.domain, base.codomain)
    if lower is None and upper is None:
        raise ValueError(
            "Truncated requires at least one of lower / upper to be finite; "
            "without truncation, use the base family directly"
        )
    if lower is not None and upper is not None and not (lower < upper):
        raise ValueError(
            f"Truncated requires lower < upper; got lower={lower}, upper={upper}"
        )
    if any(
        bound is not None and not math.isfinite(bound) for bound in (lower, upper)
    ):
        raise ValueError("Truncated bounds must be finite or None")
    if (
        isinstance(max_rejection_iterations, bool)
        or not isinstance(max_rejection_iterations, int)
        or max_rejection_iterations < 1
    ):
        raise ValueError("max_rejection_iterations must be a positive integer")
    self._base = base
    self._lower = lower
    self._upper = upper
    self._max_iters = max_rejection_iterations
    base_support = getattr(base, "support", _constraints.real)
    base_lower = getattr(base_support, "lower_bound", None)
    base_upper = getattr(base_support, "upper_bound", None)
    effective_lower, effective_upper = lower, upper
    if isinstance(base_lower, (float, int)):
        effective_lower = base_lower if lower is None else max(lower, base_lower)
    if isinstance(base_upper, (float, int)):
        effective_upper = base_upper if upper is None else min(upper, base_upper)
    if getattr(base_support, "is_discrete", False):
        self.support = _constraints.integer_interval(
            -math.inf if effective_lower is None else math.ceil(effective_lower),
            math.inf if effective_upper is None else math.floor(effective_upper),
        )
    elif effective_lower is not None and effective_upper is not None:
        self.support = _constraints.interval(effective_lower, effective_upper)
    elif effective_lower is not None:
        self.support = _constraints.greater_than(effective_lower)
    elif effective_upper is not None:
        self.support = _constraints.less_than(effective_upper)
    # Attach so the parent nn.Module tracks parameters.
    self._base_mod = base

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Condition each independent coordinate on the supplied interval.

Source code in src/quivers/continuous/families.py
def rsample(
    self, x: torch.Tensor, sample_shape: torch.Size = torch.Size()
) -> torch.Tensor:
    """Condition each independent coordinate on the supplied interval."""
    from quivers.continuous.measure import _bounded_rejection

    shape = torch.Size(sample_shape)
    builder = getattr(self._base, "_get_dist", None)
    if callable(builder):
        distribution = builder(x)
        if distribution.event_shape:
            raise NotImplementedError(
                "Truncated sampling of coupled events requires a joint rectangle law"
            )
        if isinstance(distribution, D.Normal):
            lower = distribution.loc.new_tensor(
                -torch.inf if self._lower is None else self._lower
            )
            upper = distribution.loc.new_tensor(
                torch.inf if self._upper is None else self._upper
            )
            return TruncatedNormal(
                distribution.loc, distribution.scale, lower, upper
            ).rsample(shape)
    return _bounded_rejection(
        lambda: self._base.rsample(x, shape),
        self._coordinate_bounds,
        max_rounds=self._max_iters,
        label="Truncated",
    )

cox_spline_basis

cox_spline_basis(event_times: Sequence[float], observed_times: Sequence[float], *, df: int = 5, degree: int = 3) -> MSplineBasis

Choose event-quantile knots within the full observed-time boundary span.

PARAMETER DESCRIPTION
event_times

Finite nonnegative times of exact, uncensored events.

TYPE: Sequence[float]

observed_times

Finite nonnegative training follow-up times, including censored rows.

TYPE: Sequence[float]

df

Requested number of normalized M-spline components, including the intercept component. Must be at least degree + 1.

TYPE: int DEFAULT: 5

degree

Polynomial degree; three gives cubic M-splines.

TYPE: int DEFAULT: 3

RETURNS DESCRIPTION
MSplineBasis

Immutable knots, degree, zero lower boundary, and constant hazard tail. The upper boundary exceeds maximum follow-up by one fiftieth of its full span, or one fiftieth of the maximum when the span is zero.

RAISES DESCRIPTION
ValueError

If training evidence cannot determine the requested distinct interior event quantiles or a positive finite boundary. Supply an explicit MSplineBasis when automatic knot selection is underdetermined.

Notes

This function belongs to training-data preparation. Prediction retains its returned basis and never selects knots from fresh covariates or responses. Censoring times can extend support but cannot move interior event quantiles.

Source code in src/quivers/_spline_design.py
def cox_spline_basis(
    event_times: Sequence[float],
    observed_times: Sequence[float],
    *,
    df: int = 5,
    degree: int = 3,
) -> MSplineBasis:
    """Choose event-quantile knots within the full observed-time boundary span.

    Parameters
    ----------
    event_times : Sequence[float]
        Finite nonnegative times of exact, uncensored events.
    observed_times : Sequence[float]
        Finite nonnegative training follow-up times, including censored rows.
    df : int
        Requested number of normalized M-spline components, including the
        intercept component. Must be at least ``degree + 1``.
    degree : int
        Polynomial degree; three gives cubic M-splines.

    Returns
    -------
    MSplineBasis
        Immutable knots, degree, zero lower boundary, and constant hazard tail.
        The upper boundary exceeds maximum follow-up by one fiftieth of its
        full span, or one fiftieth of the maximum when the span is zero.

    Raises
    ------
    ValueError
        If training evidence cannot determine the requested distinct interior
        event quantiles or a positive finite boundary. Supply an explicit
        MSplineBasis when automatic knot selection is underdetermined.

    Notes
    -----
    This function belongs to training-data preparation. Prediction retains its
    returned basis and never selects knots from fresh covariates or responses.
    Censoring times can extend support but cannot move interior event quantiles.
    """
    if isinstance(degree, bool) or not isinstance(degree, int) or degree < 0:
        raise ValueError("spline degree must be a nonnegative integer")
    if isinstance(df, bool) or not isinstance(df, int) or df < degree + 1:
        raise ValueError("spline df must be an integer at least degree + 1")
    for values in (event_times, observed_times):
        if any(
            isinstance(t, bool)
            or not isinstance(t, Real)
            or not math.isfinite(t)
            or t < 0
            for t in values
        ):
            raise ValueError("training spline times must be finite and nonnegative")
    if not observed_times:
        raise ValueError("automatic spline knots require observed follow-up times")
    lower, maximum = min(observed_times), max(observed_times)
    if maximum <= 0:
        raise ValueError(
            "automatic spline knots require positive follow-up; supply an explicit basis"
        )
    if event_times and max(event_times) > maximum:
        raise ValueError("event times cannot exceed the full observed-time span")
    span = maximum - lower
    upper = maximum + (span if span else maximum) / 50
    if not math.isfinite(upper):
        raise ValueError(
            "automatic spline upper boundary is not finite; supply an explicit basis"
        )
    count = df - degree - 1
    events = sorted(map(float, event_times))
    if count and not events:
        raise ValueError(
            "event quantiles require exact events; supply an explicit basis"
        )
    knots = []
    for j in range(1, count + 1):
        rank = (len(events) - 1) * j / (count + 1)
        index = math.floor(rank)
        fraction = rank - index
        following = min(index + 1, len(events) - 1)
        knots.append((1 - fraction) * events[index] + fraction * events[following])
    if any(a >= b for a, b in zip((0.0, *knots), (*knots, upper))):
        raise ValueError(
            "event quantiles are not distinct interior knots; supply an explicit basis"
        )
    return MSplineBasis((0.0, float(upper)), tuple(knots), degree)

Asymmetric Laplace quantiles

AsymmetricLaplace(loc, scale, quantile) models a selected response quantile; ConditionalAsymmetricLaplace learns all three parameters from its input. The native distribution provides differentiable sampling, density, CDF, inverse CDF, mean, variance, and entropy. Its scale follows the check-loss convention used in brms quantile regression: at quantile 0.5, it equals Laplace(loc, 2 * scale).

_asymmetric_laplace

Asymmetric Laplace distributions in the quantile regression parameterization.

AsymmetricLaplace

AsymmetricLaplace(loc: Tensor | float, scale: Tensor | float, quantile: Tensor | float, validate_args: bool | None = None)

Bases: Distribution

Asymmetric Laplace distribution parameterized by a response quantile.

The density is q * (1-q) / scale * exp(-rho_q((y-loc)/scale)), where rho_q(u) = u * (q - I[u < 0]). Thus P(Y < loc) = q; loc is the modeled quantile, and generally differs from the mean. At q=0.5, this is Laplace(loc, 2 * scale).

PARAMETER DESCRIPTION
loc

Location of the specified quantile.

TYPE: Tensor or float

scale

Strictly positive scale in the check-loss parameterization.

TYPE: Tensor or float

quantile

Probability strictly between zero and one.

TYPE: Tensor or float

validate_args

Whether to validate distribution parameters and evaluation points.

TYPE: bool or None DEFAULT: None

Notes

Sampling uses the difference of independent exponential variables. It is reparameterized in all three parameters and requires no rejection loop, inverse-CDF endpoint clamp, or discrete branch draw.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def __init__(
    self,
    loc: Tensor | float,
    scale: Tensor | float,
    quantile: Tensor | float,
    validate_args: bool | None = None,
) -> None:
    self.loc, self.scale, self.quantile = broadcast_all(loc, scale, quantile)
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean: Tensor

Expected response, which generally differs from the quantile location.

RETURNS DESCRIPTION
Tensor

Response mean.

mode property

mode: Tensor

Most probable continuous response.

RETURNS DESCRIPTION
Tensor

Component quantile location.

variance property

variance: Tensor

Response variance from the two exponential components.

RETURNS DESCRIPTION
Tensor

Response variance.

expand

expand(batch_shape, _instance=None)

Expand parameter views over a new batch.

PARAMETER DESCRIPTION
batch_shape

Target batch dimensions.

TYPE: Size

_instance

Optional reusable distribution instance.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
AsymmetricLaplace

Expanded parameter views.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views over a new batch.

    Parameters
    ----------
    batch_shape : torch.Size
        Target batch dimensions.
    _instance : Distribution or None
        Optional reusable distribution instance.

    Returns
    -------
    AsymmetricLaplace
        Expanded parameter views.
    """
    new = self._get_checked_instance(AsymmetricLaplace, _instance)
    shape = torch.Size(batch_shape)
    new.loc = self.loc.expand(shape)
    new.scale = self.scale.expand(shape)
    new.quantile = self.quantile.expand(shape)
    super(AsymmetricLaplace, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value: Tensor) -> Tensor

Evaluate the check-loss density.

PARAMETER DESCRIPTION
value

Real response values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log Lebesgue density.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def log_prob(self, value: Tensor) -> Tensor:
    """Evaluate the check-loss density.

    Parameters
    ----------
    value : Tensor
        Real response values.

    Returns
    -------
    Tensor
        Log Lebesgue density.
    """
    if self._validate_args:
        self._validate_sample(value)
    q = self.quantile
    finite = torch.isfinite(value)
    point = torch.where(finite, value, self.loc)
    residual = (point - self.loc) / self.scale
    loss = torch.where(residual < 0, (q - 1) * residual, q * residual)
    result = q.log() + torch.log1p(-q) - self.scale.log() - loss
    return torch.where(finite, result, -torch.inf)

log_cdf

log_cdf(value: Tensor) -> Tensor

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Real evaluation points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log probability of a response at or below each point.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def log_cdf(self, value: Tensor) -> Tensor:
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Real evaluation points.

    Returns
    -------
    Tensor
        Log probability of a response at or below each point.
    """
    return self._log_tails(value)[0]

log_survival_function

log_survival_function(value: Tensor) -> Tensor

Evaluate strict survival probabilities directly in log space.

PARAMETER DESCRIPTION
value

Real evaluation points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log probability of a response strictly above each point.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def log_survival_function(self, value: Tensor) -> Tensor:
    """Evaluate strict survival probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Real evaluation points.

    Returns
    -------
    Tensor
        Log probability of a response strictly above each point.
    """
    return self._log_tails(value)[1]

cdf

cdf(value: Tensor) -> Tensor

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Real evaluation points.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Probability of a response at or below each point.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def cdf(self, value: Tensor) -> Tensor:
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Real evaluation points.

    Returns
    -------
    Tensor
        Probability of a response at or below each point.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value: Tensor) -> Tensor

Invert cumulative probabilities with safe endpoint derivatives.

PARAMETER DESCRIPTION
value

Probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Continuous response quantiles.

RAISES DESCRIPTION
ValueError

If probabilities are outside the closed unit interval.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def icdf(self, value: Tensor) -> Tensor:
    """Invert cumulative probabilities with safe endpoint derivatives.

    Parameters
    ----------
    value : Tensor
        Probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Continuous response quantiles.

    Raises
    ------
    ValueError
        If probabilities are outside the closed unit interval.
    """
    if self._validate_args:
        demand(
            constraints.unit_interval.check(value),
            lambda: ValueError(
                "AsymmetricLaplace.icdf requires probabilities in [0, 1]"
            ),
        )
    q = self.quantile
    interior = (value > 0) & (value < 1)
    probability = torch.where(interior, value, 0.5)
    is_left = probability < q
    left_point = torch.where(is_left, probability, q)
    right_point = torch.where(is_left, q, probability)
    left = (left_point.log() - q.log()) / (1 - q)
    right = -(torch.log1p(-right_point) - torch.log1p(-q)) / q
    result = self.loc + self.scale * torch.where(is_left, left, right)
    result = torch.where(value == 0, -torch.inf, result)
    return torch.where(value == 1, torch.inf, result)

entropy

entropy() -> Tensor

Differential entropy of the component law.

RETURNS DESCRIPTION
Tensor

Entropy in natural logarithmic units.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def entropy(self) -> Tensor:
    """Differential entropy of the component law.

    Returns
    -------
    Tensor
        Entropy in natural logarithmic units.
    """
    q = self.quantile
    return 1 + self.scale.log() - q.log() - torch.log1p(-q)

rsample

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

Draw reparameterized differences of independent exponentials.

PARAMETER DESCRIPTION
sample_shape

Dimensions prepended to the parameter batch.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Reparameterized response samples.

Source code in src/quivers/continuous/_asymmetric_laplace.py
def rsample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draw reparameterized differences of independent exponentials.

    Parameters
    ----------
    sample_shape : torch.Size
        Dimensions prepended to the parameter batch.

    Returns
    -------
    Tensor
        Reparameterized response samples.
    """
    shape = self._extended_shape(sample_shape)
    noise = torch.empty(
        (2, *shape), dtype=self.loc.dtype, device=self.loc.device
    ).exponential_()
    return self.loc + self.scale * (
        noise[0] / self.quantile - noise[1] / (1 - self.quantile)
    )

COM-Poisson counts

COMPoisson accepts exactly one of rate and log_rate, together with positive dispersion. ConditionalCOMPoisson learns native rate and dispersion. The family has mass proportional to rate**k / factorial(k)**dispersion; zero rate is a point mass at zero. Parameters, log scores, and moments use float64; samples use int64 and provide no pathwise gradient.

Centered sums certify omitted mass and weighted moments with default normalization_rtol=1e-12 and max_terms=262144 candidate cells. Failure to certify within the budget raises NotImplementedError. The exact log-concave rejection sampler has its own max_proposals=10000 round budget and raises RuntimeError on proposal or count-capacity failure. It does not sample a truncated normalization table. Native and checked-reference execution are supported; all 11 external targets refuse this family. CDF and inverse-CDF operations, thus censoring and interval truncation, remain unavailable.

_com_poisson

Conway--Maxwell--Poisson counts with certified sums and exact rejection.

COMPoisson

COMPoisson(rate=None, dispersion=1.0, *, log_rate=None, validate_args=None, normalization_rtol=1e-12, max_terms=262144, max_proposals=10000)

Bases: Distribution

Counts proportional to rate**k / (k!)**dispersion.

PARAMETER DESCRIPTION
rate

Nonnegative rate. Supply exactly one of rate and log_rate.

TYPE: Tensor or float or None DEFAULT: None

dispersion

Strictly positive dispersion exponent.

TYPE: Tensor or float DEFAULT: 1.0

log_rate

Logarithm of the rate, permitting rates beyond floating-point range.

TYPE: Tensor or float or None DEFAULT: None

validate_args

Whether to validate parameters and samples.

TYPE: bool or None DEFAULT: None

normalization_rtol

Certified relative tail tolerance for normalization and moments.

TYPE: float DEFAULT: 1e-12

max_terms

Maximum centered count cells per row before an explicit refusal.

TYPE: int DEFAULT: 262144

max_proposals

Maximum rejection rounds per requested sample.

TYPE: int DEFAULT: 10000

Source code in src/quivers/continuous/_com_poisson.py
def __init__(
    self,
    rate=None,
    dispersion=1.0,
    *,
    log_rate=None,
    validate_args=None,
    normalization_rtol=1e-12,
    max_terms=262144,
    max_proposals=10000,
):
    if (rate is None) == (log_rate is None):
        raise ValueError("COMPoisson requires exactly one of rate and log_rate")
    if (
        not 0 < normalization_rtol < 1
        or not isinstance(max_terms, int)
        or not isinstance(max_proposals, int)
        or max_terms < 1
        or max_proposals < 1
    ):
        raise ValueError(
            "COMPoisson tolerances and resource budgets must be positive"
        )
    first, self.dispersion = _broadcast_count_parameters(
        log_rate if rate is None else rate, dispersion
    )
    if rate is None:
        self.log_rate = first
        self.rate = first.exp()
        self._boundary_rate = torch.zeros_like(first)
    else:
        self.rate = first
        self._boundary_rate = first
        demand(
            torch.isfinite(first) & (first >= 0),
            lambda: ValueError("COMPoisson rate must be finite and nonnegative"),
        )
        positive = first > 0
        self.log_rate = torch.where(
            positive, torch.where(positive, first, 1.0).log(), -torch.inf
        )
    demand(
        torch.isfinite(self.dispersion) & (self.dispersion > 0),
        lambda: ValueError("COMPoisson dispersion must be finite and positive"),
    )
    demand(
        torch.isfinite(self.log_rate) | (self.log_rate == -torch.inf),
        lambda: ValueError(
            "COMPoisson log_rate must be finite or negative infinity"
        ),
    )
    self.normalization_rtol = normalization_rtol
    self.max_terms = max_terms
    self.max_proposals = max_proposals
    # The negative-infinite log rate is the admitted zero-rate limit.
    super().__init__(self.dispersion.shape, validate_args=False)
    self._validate_args = bool(validate_args)

mean property

mean

Return a certified response mean.

RETURNS DESCRIPTION
Tensor

Float64 response means.

variance property

variance

Return a certified response variance.

RETURNS DESCRIPTION
Tensor

Float64 response variances.

expand

expand(batch_shape, _instance=None)

Expand parameter views while retaining the numerical policy.

PARAMETER DESCRIPTION
batch_shape

Requested batch shape.

TYPE: Size or Sequence[int]

_instance

Unused torch expansion hook.

TYPE: COMPoisson or None DEFAULT: None

RETURNS DESCRIPTION
COMPoisson

Expanded distribution.

Source code in src/quivers/continuous/_com_poisson.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views while retaining the numerical policy.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested batch shape.
    _instance : COMPoisson or None
        Unused torch expansion hook.

    Returns
    -------
    COMPoisson
        Expanded distribution.
    """
    result = COMPoisson(
        log_rate=self.log_rate.expand(batch_shape),
        dispersion=self.dispersion.expand(batch_shape),
        validate_args=self._validate_args,
        normalization_rtol=self.normalization_rtol,
        max_terms=self.max_terms,
        max_proposals=self.max_proposals,
    )
    result._boundary_rate = self._boundary_rate.expand(batch_shape)
    return result

log_prob

log_prob(value)

Score counts with a certified centered normalizer.

PARAMETER DESCRIPTION
value

Candidate count values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Float64 log masses, negative infinity off support.

Source code in src/quivers/continuous/_com_poisson.py
def log_prob(self, value):
    """Score counts with a certified centered normalizer.

    Parameters
    ----------
    value : Tensor
        Candidate count values.

    Returns
    -------
    Tensor
        Float64 log masses, negative infinity off support.
    """
    _check_count_observation_source(value)
    value = torch.as_tensor(
        value, device=self.dispersion.device, dtype=torch.float64
    )
    if self._validate_args:
        self._validate_sample(value)
    mode, log_sum, _, _ = self._statistics()
    log_rate, nu, _ = self._parameters()
    valid = torch.isfinite(value) & (value >= 0) & (value == value.floor())
    result = (
        _relative_weight(torch.where(valid, value, 0.0), log_rate, nu, mode)
        - log_sum
    )
    result = torch.where(
        self.log_rate == -torch.inf,
        torch.where(value == 0, -self._boundary_rate, -torch.inf),
        result,
    )
    return torch.where(valid, result, -torch.inf)

sample

sample(sample_shape=Size())

Sample from a log-concave envelope without truncating the law.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 count samples.

RAISES DESCRIPTION
RuntimeError

If a proposal exceeds exact count capacity or the round budget.

Source code in src/quivers/continuous/_com_poisson.py
def sample(self, sample_shape=torch.Size()):
    """Sample from a log-concave envelope without truncating the law.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Int64 count samples.

    Raises
    ------
    RuntimeError
        If a proposal exceeds exact count capacity or the round budget.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        log_rate = self.log_rate.expand(shape).reshape(-1)
        nu = self.dispersion.expand(shape).reshape(-1)
        output = torch.zeros_like(log_rate)
        active = torch.nonzero(torch.isfinite(log_rate), as_tuple=True)[0]
        for _ in range(self.max_proposals):
            if active.numel() == 0:
                return output.reshape(shape).to(torch.int64)
            lr, power = log_rate[active], nu[active]
            rho = _require_sample_capacity((lr / power).exp())
            mode = rho.floor()
            width = (rho / power).sqrt().clamp_min(1)
            left = (mode - width.ceil()).clamp_min(0)
            right = _require_sample_capacity(mode + width.ceil())
            log_lratio = power * left.clamp_min(1).log() - lr
            log_rratio = lr - power * (right + 1).log()
            lweight = _relative_weight(left, lr, power, mode)
            rweight = _relative_weight(right, lr, power, mode)
            lmass = torch.where(
                left > 0,
                (lweight + log_lratio).exp() / -torch.expm1(log_lratio),
                0.0,
            )
            rmass = (rweight + log_rratio).exp() / -torch.expm1(log_rratio)
            middle = right - left + 1
            pick = torch.rand_like(lr) * (middle + lmass + rmass)
            in_left = pick < lmass
            in_right = pick >= lmass + middle
            u = torch.rand_like(lr).clamp_min(torch.finfo(torch.float64).tiny)
            safe_lratio = torch.where(left > 0, log_lratio, -1.0)
            lj = (u.log() / safe_lratio).floor() + 1
            rj = (u.log() / log_rratio).floor() + 1
            center = left + (torch.rand_like(lr) * middle).floor()
            candidate = torch.where(
                in_left, left - lj, torch.where(in_right, right + rj, center)
            )
            nonnegative = candidate >= 0
            _require_sample_capacity(candidate.clamp_min(0))
            envelope = torch.where(
                in_left,
                lweight + lj * log_lratio,
                torch.where(in_right, rweight + rj * log_rratio, 0.0),
            )
            actual = _relative_weight(candidate.clamp_min(0), lr, power, mode)
            accept = nonnegative & (torch.rand_like(lr).log() <= actual - envelope)
            output[active[accept]] = candidate[accept]
            active = active[~accept]
    raise RuntimeError("COMPoisson rejection sampling exhausted max_proposals")

Vector count events

Multinomial(total_count, probs=...) and Multinomial(total_count, logits=...) choose exclusive parameterizations; DirichletMultinomial(total_count, concentration) adds a positive concentration vector. Their trailing category axis is one event, independent of batch axes. A batch may have heterogeneous trial counts. Every event has nonnegative integer coordinates summing to its trial count; zero trials give an all-zero vector, including for a single category.

Trial counts are checked before floating conversion and lie in 0..2**53. Parameters, scores, means, and variances use float64; discrete samples use int64 without pathwise reparameterization. Dirichlet-multinomial concentration sums must remain finite. ConditionalMultinomial learns category logits and ConditionalDirichletMultinomial learns positive concentrations, with fixed trials passed to each conditional constructor.

Native and checked-reference execution support both kernels. The source example keeps row dimensions separate from the category event axis. External rendering is a separate capability from these native interfaces.

_multinomial

Vector counts with heterogeneous trials and stable conditional scores.

Multinomial

Multinomial(total_count, probs=None, logits=None, validate_args=None)

Bases: Distribution

Multinomial events with a separate trial count on each batch row.

PARAMETER DESCRIPTION
total_count

Nonnegative integer trials, exactly representable through 2**53.

TYPE: Tensor or int

probs

Finite nonnegative category weights with a positive row total.

TYPE: Tensor or Sequence[float] or None DEFAULT: None

logits

Alternative category log weights; provide exactly one representation.

TYPE: Tensor or Sequence[float] or None DEFAULT: None

validate_args

Whether to validate observation support through torch.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_multinomial.py
def __init__(self, total_count, probs=None, logits=None, validate_args=None):
    if (probs is None) == (logits is None):
        raise ValueError("Multinomial requires exactly one of probs and logits")
    vector = probs if probs is not None else logits
    self.total_count, parameter = _count_parameters(total_count, vector)
    self._from_probs = probs is not None
    self._parameter = parameter
    # Validate the original representation before zero-trial masking.
    with torch.no_grad():
        if probs is not None:
            _ValidatedCategorical(probs=parameter)
        else:
            valid = torch.isfinite(parameter) | (parameter == -torch.inf)
            demand(
                valid.all(-1) & torch.isfinite(parameter).any(-1),
                lambda: ValueError(
                    "Multinomial logits require a finite category and no NaN or positive infinity"
                ),
            )
            _ValidatedCategorical(logits=parameter)
    super().__init__(
        self.total_count.shape,
        torch.Size((parameter.shape[-1],)),
        validate_args=False,
    )
    self._validate_args = bool(validate_args)

mean property

mean

Expected category counts.

RETURNS DESCRIPTION
Tensor

Float64 counts on the batch and category axes.

variance property

variance

Marginal category variances.

RETURNS DESCRIPTION
Tensor

Float64 variances on batch and category axes.

probs

probs()

Normalized category probabilities, retaining the original zero-trial input.

RETURNS DESCRIPTION
Tensor

Probabilities on batch and category axes.

Source code in src/quivers/continuous/_multinomial.py
@lazy_property
def probs(self):
    """Normalized category probabilities, retaining the original zero-trial input.

    Returns
    -------
    Tensor
        Probabilities on batch and category axes.
    """
    return self._categorical().probs

logits

logits()

Normalized category log weights with exact structural zeros.

RETURNS DESCRIPTION
Tensor

Log probabilities on batch and category axes.

Source code in src/quivers/continuous/_multinomial.py
@lazy_property
def logits(self):
    """Normalized category log weights with exact structural zeros.

    Returns
    -------
    Tensor
        Log probabilities on batch and category axes.
    """
    return self._categorical().logits

expand

expand(batch_shape, _instance=None)

Expand parameter views while preserving category event axes.

PARAMETER DESCRIPTION
batch_shape

Requested batch shape.

TYPE: Size or Sequence[int]

_instance

Optional torch expansion instance.

TYPE: Multinomial or None DEFAULT: None

RETURNS DESCRIPTION
Multinomial

Expanded distribution with unchanged category count.

Source code in src/quivers/continuous/_multinomial.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views while preserving category event axes.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested batch shape.
    _instance : Multinomial or None
        Optional torch expansion instance.

    Returns
    -------
    Multinomial
        Expanded distribution with unchanged category count.
    """
    new = self._get_checked_instance(type(self), _instance)
    batch_shape = torch.Size(batch_shape)
    new.total_count = self.total_count.expand(batch_shape)
    new._parameter = self._parameter.expand(*batch_shape, *self.event_shape)
    new._from_probs = self._from_probs
    Distribution.__init__(new, batch_shape, self.event_shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Score whole count vectors by stable conditional binomial masses.

PARAMETER DESCRIPTION
value

Count events with the declared trailing category axis.

TYPE: Tensor or Sequence[int]

RETURNS DESCRIPTION
Tensor

One Float64 log mass per sample and batch event.

Source code in src/quivers/continuous/_multinomial.py
def log_prob(self, value):
    """Score whole count vectors by stable conditional binomial masses.

    Parameters
    ----------
    value : Tensor or Sequence[int]
        Count events with the declared trailing category axis.

    Returns
    -------
    Tensor
        One Float64 log mass per sample and batch event.
    """
    point, n, valid = _count_event(value, self.total_count, self.event_shape[0])
    active = valid & (n > 0)
    categorical = self._categorical(active)
    n = torch.where(valid, n, 0.0)
    if self.event_shape[0] == 1:
        return torch.where(valid, n * 0 + categorical.probs.sum(-1) * 0, -torch.inf)
    remaining = _remaining_counts(point, n)
    k = point[..., :-1]
    if self._from_probs:
        probabilities = categorical.probs
        tail = probabilities.flip(-1).cumsum(-1).flip(-1)
        denom = tail[..., :-1]
        p = torch.where(
            denom > 0,
            probabilities[..., :-1] / torch.where(denom > 0, denom, 1.0),
            0.0,
        )
        scores = ClosedBinomial(remaining, probs=p, validate_args=False).log_prob(k)
    else:
        logits = cast(Tensor, categorical.logits)
        tail = _log_tails(logits)
        active = torch.isfinite(tail[..., :-1])
        base = torch.where(active, tail[..., :-1], 0.0)
        log_p = logits[..., :-1] - base
        log_q = tail[..., 1:] - base
        ordinary = active & torch.isfinite(log_p) & torch.isfinite(log_q)
        scores = _binomial_log_mass(
            k,
            remaining,
            torch.where(ordinary, log_p, -0.6931471805599453),
            torch.where(ordinary, log_q, -0.6931471805599453),
        )
        left = torch.where(
            k == 0, 0.0, k * torch.where(torch.isfinite(log_p), log_p, 0.0)
        )
        right = torch.where(
            remaining == k,
            0.0,
            (remaining - k) * torch.where(torch.isfinite(log_q), log_q, 0.0),
        )
        endpoint = left + right
        impossible = ((k > 0) & ~torch.isfinite(log_p)) | (
            (remaining > k) & ~torch.isfinite(log_q)
        )
        endpoint = torch.where(impossible, -torch.inf, endpoint)
        scores = torch.where(ordinary, scores, endpoint)
    return torch.where(valid, scores.sum(-1), -torch.inf)

sample

sample(sample_shape: Size | Sequence[int] = Size())

Draw Int64 events in O(categories times rows) work.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 events with exactly the requested trial totals.

Source code in src/quivers/continuous/_multinomial.py
def sample(self, sample_shape: torch.Size | Sequence[int] = torch.Size()):
    """Draw Int64 events in O(categories times rows) work.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Int64 events with exactly the requested trial totals.
    """
    with torch.no_grad():
        return _multinomial_sample(
            self.total_count,
            self._categorical(self.total_count > 0).probs,
            sample_shape,
        )

DirichletMultinomial

DirichletMultinomial(total_count, concentration, validate_args=None)

Bases: Distribution

Multinomial events with Dirichlet-distributed category probabilities.

PARAMETER DESCRIPTION
total_count

Nonnegative integer trials through 2**53 on the batch axes.

TYPE: Tensor or int

concentration

Finite strictly positive category concentrations.

TYPE: Tensor or Sequence[float]

validate_args

Whether torch validates normalized parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_multinomial.py
def __init__(self, total_count, concentration, validate_args=None):
    self.total_count, self.concentration = _count_parameters(
        total_count, concentration
    )
    demand(
        torch.isfinite(self.concentration) & (self.concentration > 0),
        lambda: ValueError(
            "DirichletMultinomial concentrations must be finite and positive"
        ),
    )
    demand(
        torch.isfinite(self.concentration.sum(-1)),
        lambda: ValueError(
            "DirichletMultinomial concentration totals exceed Float64 capacity"
        ),
    )
    super().__init__(
        self.total_count.shape,
        torch.Size((self.concentration.shape[-1],)),
        validate_args=validate_args,
    )

mean property

mean

Expected category counts.

RETURNS DESCRIPTION
Tensor

Float64 counts including exact zero-trial rows.

variance property

variance

Marginal category variances, including Dirichlet overdispersion.

RETURNS DESCRIPTION
Tensor

Float64 marginal variances.

expand

expand(batch_shape, _instance=None)

Expand trials and concentration views without merging event axes.

PARAMETER DESCRIPTION
batch_shape

Requested batch shape.

TYPE: Size or Sequence[int]

_instance

Optional torch expansion instance.

TYPE: DirichletMultinomial or None DEFAULT: None

RETURNS DESCRIPTION
DirichletMultinomial

Expanded count-vector distribution.

Source code in src/quivers/continuous/_multinomial.py
def expand(self, batch_shape, _instance=None):
    """Expand trials and concentration views without merging event axes.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested batch shape.
    _instance : DirichletMultinomial or None
        Optional torch expansion instance.

    Returns
    -------
    DirichletMultinomial
        Expanded count-vector distribution.
    """
    new = self._get_checked_instance(type(self), _instance)
    batch_shape = torch.Size(batch_shape)
    new.total_count = self.total_count.expand(batch_shape)
    new.concentration = self.concentration.expand(*batch_shape, *self.event_shape)
    Distribution.__init__(new, batch_shape, self.event_shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Score the event using its exact conditional beta-binomial factorization.

PARAMETER DESCRIPTION
value

Count vectors on the trailing category axis.

TYPE: Tensor or Sequence[int]

RETURNS DESCRIPTION
Tensor

Float64 log masses on the sample and batch axes.

Source code in src/quivers/continuous/_multinomial.py
def log_prob(self, value):
    """Score the event using its exact conditional beta-binomial factorization.

    Parameters
    ----------
    value : Tensor or Sequence[int]
        Count vectors on the trailing category axis.

    Returns
    -------
    Tensor
        Float64 log masses on the sample and batch axes.
    """
    point, n, valid = _count_event(value, self.total_count, self.event_shape[0])
    n = torch.where(valid, n, 0.0)
    concentration = torch.where((n > 0).unsqueeze(-1), self.concentration, 1.0)
    if self.event_shape[0] == 1:
        return torch.where(valid, n * 0 + concentration.sum(-1) * 0, -torch.inf)
    tail = concentration.flip(-1).cumsum(-1).flip(-1)
    scores = _beta_binomial_log_mass(
        point[..., :-1],
        _remaining_counts(point, n),
        concentration[..., :-1],
        tail[..., 1:],
    )
    return torch.where(valid, scores.sum(-1), -torch.inf)

sample

sample(sample_shape: Size | Sequence[int] = Size())

Draw Dirichlet weights and use the shared heterogeneous-trial sampler.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 count events with exact trial totals.

Source code in src/quivers/continuous/_multinomial.py
def sample(self, sample_shape: torch.Size | Sequence[int] = torch.Size()):
    """Draw Dirichlet weights and use the shared heterogeneous-trial sampler.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Int64 count events with exact trial totals.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        totals = self.total_count.expand(shape[:-1])
        concentration = self.concentration.expand(shape)
        active = totals > 0
        result = torch.zeros(shape, dtype=torch.int64, device=totals.device)
        if bool(active.any()):
            probabilities = _dirichlet_weights(concentration[active])
            result[active] = _multinomial_sample(totals[active], probabilities)
        return result

Bernstein and spline baseline hazards

BernsteinHazard(breaks, controls, rate=...) defines a positive-time proportional-hazards law. breaks has intrinsic shape [s + 1] and controls has shape [s, k]; the event itself is scalar. The dependent family signature checks this relation independently of observation batch axes. Boundaries start at zero and increase strictly. Positive Bernstein coefficients integrate to one over the retained interval, within numerical simplex tolerance, fixing baseline scale separately from the rate.

After the final boundary, the endpoint hazard continues constantly and positively. Survival thus tends to zero; the kernel retains all tail mass. Pass exactly one of rate and log_rate. The latter avoids forming an unnecessary exponential. The native implementation evaluates parameters and scores in float64, preserving gradients to original learned tensors.

CoxPH(basis, weights, ...) contracts an immutable MSplineBasis with positive simplex weights and delegates to this same kernel. It retains knots, degree, and tail policy. cox_spline_basis places interior knots using event times and sets the upper boundary from all follow-up times; new observations reuse the resulting basis. Explicit knots are required when the requested distinct event quantiles are unavailable.

ConditionalBernsteinHazard learns only the log rate over explicitly given fixed baseline tables. It validates and copies those tables; neural heads do not construct unconstrained knots or coefficients. Source programs can pass differentiable controls explicitly instead.

Both kernels provide density, CDF, log tails, inverse CDF, and pathwise sampling. The inverse uses a bounded safeguarded solve within the interval and an analytic constant-hazard tail; numerical capacity or convergence failures raise explicitly. Analytic response moments are unavailable. Native and checked-reference execution support the typed source family; external family rendering remains an explicit capability check.

_bernstein_hazard

Normalized positive Bernstein baseline hazards with an explicit tail.

BernsteinHazard

BernsteinHazard(breaks, controls, rate=None, *, log_rate=None, validate_args=None)

Bases: Distribution

A normalized positive baseline hazard and a proportional rate.

PARAMETER DESCRIPTION
breaks

Strictly increasing finite boundaries with trailing shape (S+1,), starting at zero.

TYPE: Tensor or Sequence[float]

controls

Positive Bernstein coefficients of trailing shape (S,K). The integrated baseline over the finite interval must equal one.

TYPE: Tensor or Sequence[Sequence[float]]

rate

Positive hazard multiplier, exclusive with log_rate.

TYPE: Tensor or float DEFAULT: None

log_rate

Finite log hazard multiplier.

TYPE: Tensor or float DEFAULT: None

validate_args

Torch parameter-validation policy.

TYPE: bool or None DEFAULT: None

Notes

The final hazard value continues constantly beyond the upper boundary. This positive tail retains total probability one. Normalizing the finite baseline integral identifies its shape separately from the rate. The immutable finite_moment_orders certificate records the first two finite moments; an analytic formula for those moments is not provided.

Source code in src/quivers/continuous/_bernstein_hazard.py
def __init__(
    self, breaks, controls, rate=None, *, log_rate=None, validate_args=None
):
    if (rate is None) == (log_rate is None):
        raise ValueError("supply exactly one of rate and log_rate")
    device = next(
        (
            value.device
            for value in (controls, breaks, rate, log_rate)
            if isinstance(value, Tensor)
        ),
        None,
    )
    if isinstance(rate, bool) or isinstance(log_rate, bool):
        raise ValueError("Bernstein hazard rate must be real, not Boolean")
    raw_breaks = (
        torch.as_tensor(breaks, device=device)
        if isinstance(breaks, Tensor)
        else torch.as_tensor(breaks, dtype=torch.float64, device=device)
    )
    raw_controls = (
        torch.as_tensor(controls, device=device)
        if isinstance(controls, Tensor)
        else torch.as_tensor(controls, dtype=torch.float64, device=device)
    )
    if raw_breaks.dtype == torch.bool or raw_controls.dtype == torch.bool:
        raise ValueError(
            "Bernstein structural parameters must be real, not Boolean"
        )
    self.breaks = raw_breaks.to(torch.float64)
    self.controls = raw_controls.to(torch.float64)
    if self.breaks.ndim < 1 or self.controls.ndim < 2:
        raise ValueError(
            "Bernstein hazard needs a boundary vector and coefficient matrix"
        )
    segments, width = self.controls.shape[-2:]
    if segments < 1 or width < 1 or self.breaks.shape[-1] != segments + 1:
        raise ValueError(
            "Bernstein boundaries[S+1] must match controls[S,K] with S,K positive"
        )
    value = rate if rate is not None else log_rate
    raw = (
        torch.as_tensor(value, device=device)
        if isinstance(value, Tensor)
        else torch.as_tensor(value, dtype=torch.float64, device=device)
    )
    if raw.dtype == torch.bool:
        raise ValueError("Bernstein hazard rate must be real, not Boolean")
    raw = raw.to(torch.float64)
    if rate is not None:
        if validate_args is not False:
            demand(
                torch.isfinite(raw) & (raw > 0),
                lambda: ValueError(
                    "Bernstein hazard rate must be finite and positive"
                ),
            )
        raw = raw.log()
    batch = torch.broadcast_shapes(
        self.breaks.shape[:-1], self.controls.shape[:-2], raw.shape
    )
    self.breaks = self.breaks.expand(*batch, segments + 1)
    self.controls = self.controls.expand(*batch, segments, width)
    self.log_rate = raw.expand(batch)
    intervals = self.breaks[..., 1:] - self.breaks[..., :-1]
    area = intervals * (self.controls / width).sum(-1)
    if validate_args is not False:
        demand(
            torch.isfinite(self.breaks).all(-1)
            & (self.breaks[..., 0] == 0)
            & ((intervals > 0) & torch.isfinite(intervals)).all(-1),
            lambda: ValueError(
                "Bernstein boundaries must start zero and increase finitely"
            ),
        )
        demand(
            torch.isfinite(self.controls) & (self.controls > 0),
            lambda: ValueError(
                "Bernstein controls must be finite and strictly positive"
            ),
        )
        demand(
            torch.isfinite(self.log_rate),
            lambda: ValueError("Bernstein log rate must be finite"),
        )
        demand(
            torch.isclose(area.sum(-1), area.new_tensor(1.0), rtol=1e-6, atol=1e-8),
            lambda: ValueError("Bernstein baseline integral must equal one"),
        )
    local = (self.controls / width) * intervals[..., None]
    prefix = torch.cat(
        (torch.zeros_like(area[..., :1]), area.cumsum(-1)[..., :-1]), -1
    )
    self._integrals = prefix[..., None] + torch.cat(
        (torch.zeros_like(local[..., :1]), local.cumsum(-1)), -1
    )
    super().__init__(batch, validate_args=validate_args)

rate property

rate

Return the proportional multiplier when representable.

RETURNS DESCRIPTION
Tensor

Exponentiated log rate. Density and tail calculations retain log-rate arithmetic even when this view overflows.

expand

expand(batch_shape, _instance=None)

Expand parameter views without rebuilding the integrated table.

PARAMETER DESCRIPTION
batch_shape

Requested leading batch dimensions.

TYPE: Size

_instance

Optional instance populated through the Torch expansion protocol.

TYPE: BernsteinHazard or None DEFAULT: None

RETURNS DESCRIPTION
BernsteinHazard

Distribution retaining the same baseline and integrated table.

Source code in src/quivers/continuous/_bernstein_hazard.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without rebuilding the integrated table.

    Parameters
    ----------
    batch_shape : torch.Size
        Requested leading batch dimensions.
    _instance : BernsteinHazard or None
        Optional instance populated through the Torch expansion protocol.

    Returns
    -------
    BernsteinHazard
        Distribution retaining the same baseline and integrated table.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    new.breaks = self.breaks.expand(*shape, self.breaks.shape[-1])
    new.controls = self.controls.expand(*shape, *self.controls.shape[-2:])
    new.log_rate = self.log_rate.expand(shape)
    new._integrals = self._integrals.expand(*shape, *self._integrals.shape[-2:])
    super(BernsteinHazard, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate the normalized time density on the nonnegative support.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Normalized log density, negative infinity outside the support.

RAISES DESCRIPTION
ValueError

If the time is NaN.

Source code in src/quivers/continuous/_bernstein_hazard.py
def log_prob(self, value):
    """Evaluate the normalized time density on the nonnegative support.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Normalized log density, negative infinity outside the support.

    Raises
    ------
    ValueError
        If the time is NaN.
    """
    value = self._value(value)
    safe = torch.where(
        torch.isfinite(value) & (value >= 0),
        value,
        self.breaks[..., -1],
    )
    hazard, _ = self._baseline(
        torch.where(safe > self.breaks[..., -1], self.breaks[..., -1], safe)
    )
    cumulative = self._cumulative(value)
    result = self.log_rate + hazard.log() - cumulative
    return torch.where(torch.isfinite(value) & (value >= 0), result, -torch.inf)

log_survival_function

log_survival_function(value)

Evaluate log survival directly from the integrated hazard.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Log survival, evaluated directly from cumulative hazard.

Source code in src/quivers/continuous/_bernstein_hazard.py
def log_survival_function(self, value):
    """Evaluate log survival directly from the integrated hazard.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Log survival, evaluated directly from cumulative hazard.
    """
    value = self._value(value)
    return -self._cumulative(value)

cdf

cdf(value)

Evaluate cumulative event probability, including exact support tails.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Cumulative event probability.

Source code in src/quivers/continuous/_bernstein_hazard.py
def cdf(self, value):
    """Evaluate cumulative event probability, including exact support tails.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Cumulative event probability.
    """
    return -torch.expm1(self.log_survival_function(value))

log_cdf

log_cdf(value)

Evaluate log CDF without subtracting small survival probabilities.

PARAMETER DESCRIPTION
value

Event time; negative and infinite values use the exact support limits.

TYPE: Tensor or float

RETURNS DESCRIPTION
Tensor

Log cumulative probability, retaining small positive probabilities.

Source code in src/quivers/continuous/_bernstein_hazard.py
def log_cdf(self, value):
    """Evaluate log CDF without subtracting small survival probabilities.

    Parameters
    ----------
    value : Tensor or float
        Event time; negative and infinite values use the exact support limits.

    Returns
    -------
    Tensor
        Log cumulative probability, retaining small positive probabilities.
    """
    value = self._value(value)
    return _log1mexp_neg_exp(self._log_cumulative(value))

icdf

icdf(value)

Invert the integrated hazard with a bounded, checked root solve.

PARAMETER DESCRIPTION
value

Probability in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Event quantile; the endpoints return zero and positive infinity.

RAISES DESCRIPTION
ValueError

If a probability is NaN or outside the unit interval.

FloatingPointError

If the finite positive quantile is unrepresentable.

RuntimeError

If the bounded root solver does not converge.

Source code in src/quivers/continuous/_bernstein_hazard.py
def icdf(self, value):
    """Invert the integrated hazard with a bounded, checked root solve.

    Parameters
    ----------
    value : Tensor
        Probability in the closed unit interval.

    Returns
    -------
    Tensor
        Event quantile; the endpoints return zero and positive infinity.

    Raises
    ------
    ValueError
        If a probability is NaN or outside the unit interval.
    FloatingPointError
        If the finite positive quantile is unrepresentable.
    RuntimeError
        If the bounded root solver does not converge.
    """
    value = torch.as_tensor(
        value, dtype=self.controls.dtype, device=self.controls.device
    )
    demand(
        ~((value < 0) | (value > 1) | torch.isnan(value)),
        lambda: ValueError(
            "Bernstein hazard quantile probability must lie in [0, 1]"
        ),
    )
    interior = (value > 0) & (value < 1)
    safe = torch.where(interior, value, value.new_tensor(0.5))
    log_target = (-torch.log1p(-safe)).log() - self.log_rate
    log_target = torch.where(
        interior, log_target, torch.full_like(log_target, -0.6931471805599453)
    )
    result = self._inverse_baseline(log_target)
    return torch.where(value == 0, 0.0, torch.where(value == 1, torch.inf, result))

rsample

rsample(sample_shape=Size())

Draw vectorized event times by inverse cumulative hazard.

PARAMETER DESCRIPTION
sample_shape

Independent sample dimensions preceding batch dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Pathwise event times from the full normalized law.

Source code in src/quivers/continuous/_bernstein_hazard.py
def rsample(self, sample_shape=torch.Size()):
    """Draw vectorized event times by inverse cumulative hazard.

    Parameters
    ----------
    sample_shape : torch.Size
        Independent sample dimensions preceding batch dimensions.

    Returns
    -------
    Tensor
        Pathwise event times from the full normalized law.
    """
    shape = self._extended_shape(sample_shape)
    exponential = torch.empty(
        shape, dtype=self.controls.dtype, device=self.controls.device
    ).exponential_()
    return self._inverse_baseline(exponential.log() - self.log_rate)

_cox

M/I-spline adapters for normalized Bernstein baseline hazards.

CoxPH

CoxPH(basis, weights, rate=None, *, log_rate=None, validate_args=None)

Bases: BernsteinHazard

Proportional hazards with a retained normalized M-spline basis.

PARAMETER DESCRIPTION
basis

Immutable fitted knots, degree, and constant endpoint tail.

TYPE: MSplineBasis

weights

Strictly positive simplex weights over basis components.

TYPE: Tensor or Sequence[float]

rate

Positive proportional multiplier, exclusive with log_rate.

TYPE: Tensor or float DEFAULT: None

log_rate

Finite log multiplier.

TYPE: Tensor or float DEFAULT: None

validate_args

Torch parameter-validation policy.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_cox.py
def __init__(self, basis, weights, rate=None, *, log_rate=None, validate_args=None):
    if basis.boundary_knots[0] != 0:
        raise ValueError("Cox baseline must start at time zero")
    self.basis = basis
    device = next(
        (v.device for v in (weights, rate, log_rate) if isinstance(v, Tensor)), None
    )
    weights = torch.as_tensor(weights, dtype=torch.float64, device=device)
    if weights.ndim < 1 or weights.shape[-1] != basis.size:
        raise ValueError(f"Cox weights need {basis.size} spline components")
    if validate_args is not False:
        demand(
            (torch.isfinite(weights) & (weights > 0)).all(-1)
            & torch.isclose(
                weights.sum(-1), weights.new_tensor(1.0), rtol=1e-6, atol=1e-8
            ),
            lambda: ValueError(
                "Cox spline weights must be a strictly positive simplex"
            ),
        )
    self.weights = weights
    controls = torch.einsum(
        "...j,ijk->...ik", weights, weights.new_tensor(basis.m_coefficients)
    )
    super().__init__(
        weights.new_tensor(basis.breaks),
        controls,
        rate,
        log_rate=log_rate,
        validate_args=validate_args,
    )
    self.weights = weights.expand(*self.batch_shape, basis.size)

expand

expand(batch_shape, _instance=None)

Expand distribution views while retaining the original fitted basis.

PARAMETER DESCRIPTION
batch_shape

Requested leading batch dimensions.

TYPE: Size

_instance

Optional instance populated by the Torch expansion protocol.

TYPE: CoxPH or None DEFAULT: None

RETURNS DESCRIPTION
CoxPH

Expanded view retaining the fitted basis and weights.

Source code in src/quivers/continuous/_cox.py
def expand(self, batch_shape, _instance=None):
    """Expand distribution views while retaining the original fitted basis.

    Parameters
    ----------
    batch_shape : torch.Size
        Requested leading batch dimensions.
    _instance : CoxPH or None
        Optional instance populated by the Torch expansion protocol.

    Returns
    -------
    CoxPH
        Expanded view retaining the fitted basis and weights.
    """
    new = super().expand(batch_shape, _instance)
    new.basis = self.basis
    new.weights = self.weights.expand(*batch_shape, self.basis.size)
    return new

spline_values

spline_values(basis: MSplineBasis, value: Tensor) -> tuple[Tensor, Tensor]

Lift the retained M/I-spline basis to differentiable tensor arguments.

PARAMETER DESCRIPTION
basis

Retained normalized M/I-spline structure.

TYPE: MSplineBasis

value

Evaluation times.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

M-spline hazards and integrated I-spline values, including the tail.

Source code in src/quivers/continuous/_cox.py
def spline_values(basis: MSplineBasis, value: Tensor) -> tuple[Tensor, Tensor]:
    """Lift the retained M/I-spline basis to differentiable tensor arguments.

    Parameters
    ----------
    basis : MSplineBasis
        Retained normalized M/I-spline structure.
    value : Tensor
        Evaluation times.

    Returns
    -------
    tuple[Tensor, Tensor]
        M-spline hazards and integrated I-spline values, including the tail.
    """
    breaks = value.new_tensor(basis.breaks)
    lower, upper = basis.boundary_knots
    finite = torch.where(torch.isfinite(value), value, value.new_tensor(upper))
    x = finite.clamp(lower, upper)
    index = torch.bucketize(x.contiguous(), breaks[1:-1], right=True)
    u = (x - breaks[index]) / (breaks[index + 1] - breaks[index])
    m = _bernstein(value.new_tensor(basis.m_coefficients)[index], u[..., None])
    integral = _bernstein(value.new_tensor(basis.i_coefficients)[index], u[..., None])
    tail_m = value.new_tensor([piece[-1] for piece in basis.m_coefficients[-1]])
    excess = torch.where(finite > upper, finite - upper, 0.0)
    integral = integral + excess[..., None] * tail_m
    m = torch.where((finite > upper)[..., None], tail_m, m)
    m = torch.where((value < lower)[..., None], 0.0, m)
    integral = torch.where((value < lower)[..., None], 0.0, integral)
    # The zero tail components remain finite rather than forming 0 * infinity.
    integral = torch.where(
        (value == torch.inf)[..., None] & (tail_m > 0), torch.inf, integral
    )
    return m, integral

MSplineBasis dataclass

MSplineBasis(boundary_knots: tuple[float, float] = (0.0, 1.0), interior_knots: tuple[float, ...] = (), degree: int = 3, tail: str = 'constant')

Normalized M-splines, integrated I-splines, and a constant hazard tail.

PARAMETER DESCRIPTION
boundary_knots

Finite increasing endpoints of the fitted spline interval.

TYPE: tuple[float, float] DEFAULT: (0.0, 1.0)

interior_knots

Strictly increasing knots inside the boundary interval.

TYPE: tuple[float, ...] DEFAULT: ()

degree

Nonnegative polynomial degree of the M-splines.

TYPE: int DEFAULT: 3

tail

Hazard continuation; currently "constant" retains each M-spline's value at the upper boundary and integrates it linearly thereafter.

TYPE: str DEFAULT: 'constant'

Notes

Every M-spline integrates to one over the fitted interval. Below its lower boundary both bases are zero. The retained knots and tail policy are part of value equality, so prediction cannot silently rebuild a training basis.

size property

size: int

Return the number of retained spline components.

RETURNS DESCRIPTION
int

Number of retained normalized spline components.

__post_init__

__post_init__()

Validate immutable knots and construct normalized basis tables.

RAISES DESCRIPTION
ValueError

If knots, degree, tail policy, or basis normalization are invalid.

NotImplementedError

If the retained table exceeds the explicit coefficient budget.

Source code in src/quivers/_splines.py
def __post_init__(self):
    """Validate immutable knots and construct normalized basis tables.

    Raises
    ------
    ValueError
        If knots, degree, tail policy, or basis normalization are invalid.
    NotImplementedError
        If the retained table exceeds the explicit coefficient budget.
    """
    if (
        isinstance(self.degree, bool)
        or not isinstance(self.degree, int)
        or self.degree < 0
    ):
        raise ValueError("M-spline degree must be a nonnegative integer")
    if self.tail != "constant":
        raise ValueError("M-spline tail must be 'constant'")
    raw = (*self.boundary_knots, *self.interior_knots)
    if any(
        isinstance(v, bool) or not isinstance(v, Real) or not math.isfinite(v)
        for v in raw
    ):
        raise ValueError("spline knots must be finite real numbers")
    if len(self.boundary_knots) != 2:
        raise ValueError("exactly two boundary knots are required")
    lower, upper = map(float, self.boundary_knots)
    interior = tuple(map(float, self.interior_knots))
    breaks = (lower, *interior, upper)
    if any(a >= b for a, b in zip(breaks, breaks[1:])):
        raise ValueError(
            "spline knots must increase strictly within their boundaries"
        )
    if not math.isfinite(upper - lower):
        raise ValueError("spline interval width must be finite")
    object.__setattr__(self, "boundary_knots", (lower, upper))
    object.__setattr__(self, "interior_knots", interior)
    object.__setattr__(self, "breaks", breaks)
    p = self.degree
    size = len(interior) + p + 1
    if (len(interior) + 1) * size * (2 * p + 3) > 1_048_576:
        raise NotImplementedError(
            "retained spline table exceeds 1,048,576 coefficients"
        )
    knots = (lower,) * (p + 1) + interior + (upper,) * (p + 1)
    integrated = [0.0] * size
    m_pieces, i_pieces = [], []
    for a, b in zip(breaks, breaks[1:]):
        pieces = [
            [float(t <= a and b <= s and t < s)] for t, s in zip(knots, knots[1:])
        ]
        for degree in range(1, p + 1):
            following = []
            for i in range(len(pieces) - 1):
                left_width = knots[i + degree] - knots[i]
                right_width = knots[i + degree + 1] - knots[i + 1]
                left = (
                    _linear_product(
                        pieces[i],
                        (a - knots[i]) / left_width,
                        (b - knots[i]) / left_width,
                    )
                    if left_width
                    else [0.0] * (degree + 1)
                )
                right = (
                    _linear_product(
                        pieces[i + 1],
                        (knots[i + degree + 1] - a) / right_width,
                        (knots[i + degree + 1] - b) / right_width,
                    )
                    if right_width
                    else [0.0] * (degree + 1)
                )
                following.append([x + y for x, y in zip(left, right)])
            pieces = following
        m_piece, i_piece = [], []
        for i, polynomial in enumerate(pieces):
            scale = (p + 1) / (knots[i + p + 1] - knots[i])
            coefficients = tuple(scale * value for value in polynomial)
            integral = [integrated[i]]
            for value in coefficients:
                integral.append(integral[-1] + (b - a) * value / (p + 1))
            integrated[i] = integral[-1]
            m_piece.append(coefficients)
            i_piece.append(tuple(integral))
        m_pieces.append(tuple(m_piece))
        i_pieces.append(tuple(i_piece))
    if any(
        not math.isclose(value, 1.0, rel_tol=2e-12, abs_tol=2e-12)
        for value in integrated
    ):
        raise ValueError("spline basis cannot be normalized at these knots")
    object.__setattr__(self, "m_coefficients", tuple(m_pieces))
    object.__setattr__(self, "i_coefficients", tuple(i_pieces))

evaluate

evaluate(value: float) -> tuple[tuple[float, ...], tuple[float, ...]]

Evaluate the hazard basis and its integral, including the tail.

PARAMETER DESCRIPTION
value

Evaluation time, including support endpoints and infinities.

TYPE: float

RETURNS DESCRIPTION
tuple[tuple[float, ...], tuple[float, ...]]

M-spline values and integrated I-spline values in component order.

RAISES DESCRIPTION
ValueError

If the time is NaN.

Source code in src/quivers/_splines.py
def evaluate(self, value: float) -> tuple[tuple[float, ...], tuple[float, ...]]:
    """Evaluate the hazard basis and its integral, including the tail.

    Parameters
    ----------
    value : float
        Evaluation time, including support endpoints and infinities.

    Returns
    -------
    tuple[tuple[float, ...], tuple[float, ...]]
        M-spline values and integrated I-spline values in component order.

    Raises
    ------
    ValueError
        If the time is NaN.
    """
    if math.isnan(value):
        raise ValueError("spline argument must not be NaN")
    lower, upper = self.boundary_knots
    if value < lower:
        return (0.0,) * self.size, (0.0,) * self.size
    if value >= upper:
        m = tuple(piece[-1] for piece in self.m_coefficients[-1])
        i = tuple(piece[-1] for piece in self.i_coefficients[-1])
        if value > upper:
            i = tuple(y + x * (value - upper) if x else y for x, y in zip(m, i))
        return m, i
    import bisect

    index = bisect.bisect_right(self.breaks, value) - 1
    u = (value - self.breaks[index]) / (self.breaks[index + 1] - self.breaks[index])
    return (
        tuple(_bernstein_value(piece, u) for piece in self.m_coefficients[index]),
        tuple(_bernstein_value(piece, u) for piece in self.i_coefficients[index]),
    )

cox_spline_basis

cox_spline_basis(event_times: Sequence[float], observed_times: Sequence[float], *, df: int = 5, degree: int = 3) -> MSplineBasis

Choose event-quantile knots within the full observed-time boundary span.

PARAMETER DESCRIPTION
event_times

Finite nonnegative times of exact, uncensored events.

TYPE: Sequence[float]

observed_times

Finite nonnegative training follow-up times, including censored rows.

TYPE: Sequence[float]

df

Requested number of normalized M-spline components, including the intercept component. Must be at least degree + 1.

TYPE: int DEFAULT: 5

degree

Polynomial degree; three gives cubic M-splines.

TYPE: int DEFAULT: 3

RETURNS DESCRIPTION
MSplineBasis

Immutable knots, degree, zero lower boundary, and constant hazard tail. The upper boundary exceeds maximum follow-up by one fiftieth of its full span, or one fiftieth of the maximum when the span is zero.

RAISES DESCRIPTION
ValueError

If training evidence cannot determine the requested distinct interior event quantiles or a positive finite boundary. Supply an explicit MSplineBasis when automatic knot selection is underdetermined.

Notes

This function belongs to training-data preparation. Prediction retains its returned basis and never selects knots from fresh covariates or responses. Censoring times can extend support but cannot move interior event quantiles.

Source code in src/quivers/_spline_design.py
def cox_spline_basis(
    event_times: Sequence[float],
    observed_times: Sequence[float],
    *,
    df: int = 5,
    degree: int = 3,
) -> MSplineBasis:
    """Choose event-quantile knots within the full observed-time boundary span.

    Parameters
    ----------
    event_times : Sequence[float]
        Finite nonnegative times of exact, uncensored events.
    observed_times : Sequence[float]
        Finite nonnegative training follow-up times, including censored rows.
    df : int
        Requested number of normalized M-spline components, including the
        intercept component. Must be at least ``degree + 1``.
    degree : int
        Polynomial degree; three gives cubic M-splines.

    Returns
    -------
    MSplineBasis
        Immutable knots, degree, zero lower boundary, and constant hazard tail.
        The upper boundary exceeds maximum follow-up by one fiftieth of its
        full span, or one fiftieth of the maximum when the span is zero.

    Raises
    ------
    ValueError
        If training evidence cannot determine the requested distinct interior
        event quantiles or a positive finite boundary. Supply an explicit
        MSplineBasis when automatic knot selection is underdetermined.

    Notes
    -----
    This function belongs to training-data preparation. Prediction retains its
    returned basis and never selects knots from fresh covariates or responses.
    Censoring times can extend support but cannot move interior event quantiles.
    """
    if isinstance(degree, bool) or not isinstance(degree, int) or degree < 0:
        raise ValueError("spline degree must be a nonnegative integer")
    if isinstance(df, bool) or not isinstance(df, int) or df < degree + 1:
        raise ValueError("spline df must be an integer at least degree + 1")
    for values in (event_times, observed_times):
        if any(
            isinstance(t, bool)
            or not isinstance(t, Real)
            or not math.isfinite(t)
            or t < 0
            for t in values
        ):
            raise ValueError("training spline times must be finite and nonnegative")
    if not observed_times:
        raise ValueError("automatic spline knots require observed follow-up times")
    lower, maximum = min(observed_times), max(observed_times)
    if maximum <= 0:
        raise ValueError(
            "automatic spline knots require positive follow-up; supply an explicit basis"
        )
    if event_times and max(event_times) > maximum:
        raise ValueError("event times cannot exceed the full observed-time span")
    span = maximum - lower
    upper = maximum + (span if span else maximum) / 50
    if not math.isfinite(upper):
        raise ValueError(
            "automatic spline upper boundary is not finite; supply an explicit basis"
        )
    count = df - degree - 1
    events = sorted(map(float, event_times))
    if count and not events:
        raise ValueError(
            "event quantiles require exact events; supply an explicit basis"
        )
    knots = []
    for j in range(1, count + 1):
        rank = (len(events) - 1) * j / (count + 1)
        index = math.floor(rank)
        fraction = rank - index
        following = min(index + 1, len(events) - 1)
        knots.append((1 - fraction) * events[index] + fraction * events[following])
    if any(a >= b for a, b in zip((0.0, *knots), (*knots, upper))):
        raise ValueError(
            "event quantiles are not distinct interior knots; supply an explicit basis"
        )
    return MSplineBasis((0.0, float(upper)), tuple(knots), degree)

Censored extended Beta responses

ExtendedBeta(mu, phi, kappa) starts from X ~ Beta(mu*phi, (1-mu)*phi) and returns clamp((1+2*kappa)*X-kappa, 0, 1). The parameter mu is the underlying Beta mean; the response mean generally differs. Precision phi is positive, 0 < mu < 1, and the extension kappa is nonnegative. At zero extension the law reduces to an ordinary Beta, with no endpoint atoms. Positive extension places the exact censored tail masses at zero and one. Scoring an endpoint evaluates its atom mass; interior observations use the affine Beta density.

Parameters, scores, moments, and draws use float64. Complementary Beta coordinates retain small endpoint distances before subtraction or sampling rounding. log_cdf includes boundary atoms, while log_cdf_left excludes them; the two survival methods use complementary strict/inclusive events. Pathwise sampling differentiates the affine map and censoring pushforward. It requires both Beta concentrations to be at least the square root of float64's smallest normal value, keeping shape-gradient denominators representable. Ordinary sampling retains the shared log-Gamma underflow fallback for smaller shapes. A mathematically interior draw that cannot be represented strictly between zero and one raises RuntimeError, rather than adding numerical atom mass.

Response means and variances use positive adaptive quadrature, bounded by moment_atol=1e-12, moment_rtol=1e-10, and moment_max_panels=4096 per batch row, processed in chunks of at most 64 rows. Tiny extensions use partial-Beta moment corrections; zero extension retains the exact Beta moments and their one-sided first extension derivatives. These derivatives do not imply that every second extension derivative exists at zero. A failed convergence or interval-resolution check raises explicitly. An inverse CDF is unavailable because the shared Beta base does not implement one. Native and checked-reference execution support this law; external renderers refuse it by family name.

_extended_beta

Symmetrically extended Beta responses censored to the unit interval.

ExtendedBeta

ExtendedBeta(mu, phi, kappa, *, moment_atol=1e-12, moment_rtol=1e-10, moment_max_panels=4096, validate_args=None)

Bases: Censored

Extend a mean/precision Beta law and censor its tails at zero and one.

PARAMETER DESCRIPTION
mu

Underlying Beta mean, strictly between zero and one.

TYPE: Tensor or float

phi

Strictly positive Beta precision.

TYPE: Tensor or float

kappa

Nonnegative extension: Y=clamp((1+2*kappa)*X-kappa,0,1).

TYPE: Tensor or float

moment_atol

Deterministic bounded-moment quadrature error budgets.

TYPE: float DEFAULT: 1e-12

moment_rtol

Deterministic bounded-moment quadrature error budgets.

TYPE: float DEFAULT: 1e-12

moment_max_panels

Per-row adaptive panel limit; work is chunked over at most64 rows.

TYPE: int DEFAULT: 4096

validate_args

Torch validation policy; parameter validity is always checked.

TYPE: bool or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If parameters or numerical budgets are invalid.

RuntimeError

If the symmetric extension cannot retain its censoring bounds in Float64.

Source code in src/quivers/continuous/_extended_beta.py
def __init__(
    self,
    mu,
    phi,
    kappa,
    *,
    moment_atol=1e-12,
    moment_rtol=1e-10,
    moment_max_panels=4096,
    validate_args=None,
):
    device = next(
        (x.device for x in (mu, phi, kappa) if isinstance(x, Tensor)), None
    )
    self.mu, self.phi, self.kappa = torch.broadcast_tensors(
        *(
            torch.as_tensor(x, dtype=torch.float64, device=device)
            for x in (mu, phi, kappa)
        )
    )
    valid = (
        (self.mu > 0)
        & (self.mu < 1)
        & (self.phi > 0)
        & (self.kappa >= 0)
        & torch.isfinite(self.mu + self.phi + self.kappa)
    )
    demand(
        valid,
        lambda: ValueError(
            "ExtendedBeta requires mu in(0,1), finite phi>0 and kappa>=0"
        ),
    )
    if (
        not isinstance(moment_max_panels, int)
        or isinstance(moment_max_panels, bool)
        or moment_max_panels < 1
        or not math.isfinite(moment_atol)
        or not math.isfinite(moment_rtol)
        or moment_atol <= 0
        or moment_rtol <= 0
    ):
        raise ValueError("ExtendedBeta moment budgets must be finite and positive")
    self.moment_atol, self.moment_rtol = moment_atol, moment_rtol
    self.moment_max_panels = moment_max_panels
    width = 1 + 2 * self.kappa
    demand(
        torch.isfinite(width),
        lambda: RuntimeError(
            "ExtendedBeta extension exceeds Float64 affine capacity"
        ),
    )
    low = self.kappa / width
    high = 0.5 + 0.5 / width
    demand(
        (low < 0.5) & (high > 0.5),
        lambda: RuntimeError(
            "ExtendedBeta censoring bounds exceed Float64 interval resolution"
        ),
    )
    beta = _AffineBeta(
        self.mu * self.phi, (1 - self.mu) * self.phi, self.kappa, self.kappa
    )
    super().__init__(beta, 0.0, 1.0)
    self._validate_args = bool(validate_args)

mean property

mean: Tensor

True censored response mean, computed with deterministic error bounds.

RETURNS DESCRIPTION
Tensor

Mean on the parameter batch axes, generally different from mu.

variance property

variance: Tensor

Positive within/between response variance without raw-moment cancellation.

RETURNS DESCRIPTION
Tensor

Variance on the parameter batch axes.

expand

expand(batch_shape, _instance=None)

Broadcast the same law and deterministic moment budgets.

PARAMETER DESCRIPTION
batch_shape

Requested parameter batch shape.

TYPE: Size or Sequence[int]

_instance

Optional Torch expansion instance.

TYPE: ExtendedBeta or None DEFAULT: None

RETURNS DESCRIPTION
ExtendedBeta

Expanded distribution, retaining the same numerical policy.

Source code in src/quivers/continuous/_extended_beta.py
def expand(self, batch_shape, _instance=None):
    """Broadcast the same law and deterministic moment budgets.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested parameter batch shape.
    _instance : ExtendedBeta or None
        Optional Torch expansion instance.

    Returns
    -------
    ExtendedBeta
        Expanded distribution, retaining the same numerical policy.
    """
    return type(self)(
        self.mu.expand(batch_shape),
        self.phi.expand(batch_shape),
        self.kappa.expand(batch_shape),
        moment_atol=self.moment_atol,
        moment_rtol=self.moment_rtol,
        moment_max_panels=self.moment_max_panels,
        validate_args=self._validate_args,
    )

sample

sample(sample_shape: Size | tuple[int, ...] | list[int] = Size())

Draw censoring atoms before rounding complementary Beta weights.

PARAMETER DESCRIPTION
sample_shape

Leading independent sample axes.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Distribution result on the requested sample and batch axes.

RAISES DESCRIPTION
RuntimeError

If the evaluation or sample exceeds the documented numerical capacity.

Source code in src/quivers/continuous/_extended_beta.py
def sample(
    self, sample_shape: torch.Size | tuple[int, ...] | list[int] = torch.Size()
):
    """Draw censoring atoms before rounding complementary Beta weights.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading independent sample axes.

    Returns
    -------
    Tensor
        Distribution result on the requested sample and batch axes.

    Raises
    ------
    RuntimeError
        If the evaluation or sample exceeds the documented numerical capacity.
    """
    with torch.no_grad():
        return cast(_AffineBeta, self.base)._sample_unit_censored(
            sample_shape, reparameterized=False
        )

rsample

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

Draw pathwise responses, refusing unrepresentable interior samples.

PARAMETER DESCRIPTION
sample_shape

Leading independent sample axes.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Distribution result on the requested sample and batch axes.

Source code in src/quivers/continuous/_extended_beta.py
def rsample(
    self, sample_shape: torch.Size | tuple[int, ...] | list[int] = torch.Size()
):
    """Draw pathwise responses, refusing unrepresentable interior samples.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading independent sample axes.

    Returns
    -------
    Tensor
        Distribution result on the requested sample and batch axes.
    """
    return cast(_AffineBeta, self.base)._sample_unit_censored(
        sample_shape, reparameterized=True
    )

Additive log-ratio Normal events

AdditiveLogRatioNormal(loc, scale_tril, reference=None) maps a correlated Normal vector of dimension d to a simplex of dimension d + 1. By default, the final component is the reference: log(y[:-1] / y[-1]) has that Normal distribution. An integer reference selects another component without reordering the response; Normal coordinates follow the remaining components in their original order. Batched reference indices may vary by observation. scale_tril is a lower-triangular Cholesky factor with a positive diagonal. Batch axes broadcast separately from the coordinate and matrix event axes. ConditionalAdditiveLogRatioNormal learns both Normal heads.

The density includes the change-of-variables term -sum(log(y)). Every component is strictly positive, and components must sum to one within the native simplex tolerance. Native sampling is pathwise; native and checked-reference scores retain the entire simplex as one event. This family differs from LogisticNormal, which retains its existing stick-breaking transform of independent Normal coordinates. Neither the Normal location nor its softmax is generally the simplex expectation.

The checked response extent is nat_add(d, 1), expressing the same dimension relationship used by native construction. All external targets report this family's missing rendering capability explicitly.

_additive_log_ratio

Correlated Gaussian additive log ratios on a simplex.

AdditiveLogRatioNormal

AdditiveLogRatioNormal(loc, scale_tril, reference=None, validate_args=None)

Bases: Distribution

A Gaussian law for log ratios against a selected simplex component.

PARAMETER DESCRIPTION
loc

Gaussian location with trailing width D.

TYPE: Tensor or Sequence[float]

scale_tril

Lower-triangular Gaussian scale with trailing shape (D, D).

TYPE: Tensor or Sequence[Sequence[float]]

reference

Reference component, broadcast over Gaussian batch dimensions. None selects the final component. Free coordinates retain the relative order of every other component.

TYPE: int or Tensor or None DEFAULT: None

validate_args

Torch distribution validation policy.

TYPE: bool or None DEFAULT: None

Notes

A draw has D + 1 components. The nonreference components retain their original order; their log ratios against the reference have the joint Gaussian law. The final component is the default reference. Analytic response means and variances are unavailable.

Source code in src/quivers/continuous/_additive_log_ratio.py
def __init__(self, loc, scale_tril, reference=None, validate_args=None):
    device = (
        loc.device
        if isinstance(loc, Tensor)
        else scale_tril.device
        if isinstance(scale_tril, Tensor)
        else None
    )
    loc = torch.as_tensor(loc, device=device)
    scale_tril = torch.as_tensor(scale_tril, device=device)
    dtype = torch.promote_types(loc.dtype, scale_tril.dtype)
    if not dtype.is_floating_point:
        dtype = torch.get_default_dtype()
    self._normal = MultivariateNormal(
        loc.to(dtype), scale_tril=scale_tril.to(dtype), validate_args=validate_args
    )
    width = self._normal.event_shape[0]
    selected = torch.as_tensor(
        width if reference is None else reference, device=device
    )
    if selected.dtype == torch.bool:
        raise ValueError(
            "AdditiveLogRatioNormal reference must be an integer component index"
        )
    demand(
        torch.isfinite(selected)
        & (selected >= 0)
        & (selected <= width)
        & (selected == selected.floor()),
        lambda: ValueError(
            "AdditiveLogRatioNormal reference must be an integer component index"
        ),
    )
    batch = torch.broadcast_shapes(self._normal.batch_shape, selected.shape)
    self._normal = self._normal.expand(batch)
    self.reference = selected.to(torch.long).expand(batch)
    self.loc = self._normal.loc
    self.scale_tril = self._normal.scale_tril
    if self.loc.shape[-1] < 1:
        raise ValueError(
            "AdditiveLogRatioNormal requires at least two simplex components"
        )
    super().__init__(
        self._normal.batch_shape,
        torch.Size((self.loc.shape[-1] + 1,)),
        validate_args=validate_args,
    )

expand

expand(batch_shape, _instance=None)

Broadcast the batch dimensions while retaining the coordinate event.

PARAMETER DESCRIPTION
batch_shape

New broadcast-compatible batch shape.

TYPE: Size

_instance

Optional instance populated by Torch's expansion protocol.

TYPE: AdditiveLogRatioNormal or None DEFAULT: None

RETURNS DESCRIPTION
AdditiveLogRatioNormal

Distribution with the requested batch shape.

Source code in src/quivers/continuous/_additive_log_ratio.py
def expand(self, batch_shape, _instance=None):
    """Broadcast the batch dimensions while retaining the coordinate event.

    Parameters
    ----------
    batch_shape : torch.Size
        New broadcast-compatible batch shape.
    _instance : AdditiveLogRatioNormal or None
        Optional instance populated by Torch's expansion protocol.

    Returns
    -------
    AdditiveLogRatioNormal
        Distribution with the requested batch shape.
    """
    new = self._get_checked_instance(AdditiveLogRatioNormal, _instance)
    new._normal = self._normal.expand(batch_shape)
    new.reference = self.reference.expand(batch_shape)
    new.loc = new._normal.loc
    new.scale_tril = new._normal.scale_tril
    super(AdditiveLogRatioNormal, new).__init__(
        torch.Size(batch_shape), self.event_shape, validate_args=False
    )
    new._validate_args = self._validate_args
    return new

rsample

rsample(sample_shape=Size())

Draw simplex values by reparameterizing the Gaussian log ratios.

PARAMETER DESCRIPTION
sample_shape

Independent sample dimensions preceding the batch dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Strictly positive simplex draws.

RAISES DESCRIPTION
FloatingPointError

If floating point underflow cannot represent an interior draw.

Source code in src/quivers/continuous/_additive_log_ratio.py
def rsample(self, sample_shape=torch.Size()):
    """Draw simplex values by reparameterizing the Gaussian log ratios.

    Parameters
    ----------
    sample_shape : torch.Size
        Independent sample dimensions preceding the batch dimensions.

    Returns
    -------
    Tensor
        Strictly positive simplex draws.

    Raises
    ------
    FloatingPointError
        If floating point underflow cannot represent an interior draw.
    """
    ratios = self._normal.rsample(sample_shape)
    logits = torch.zeros(
        (*ratios.shape[:-1], self.event_shape[0]),
        dtype=ratios.dtype,
        device=ratios.device,
    )
    indices = self._coordinate_indices(ratios.shape[:-1])
    values = logits.scatter(-1, indices, ratios).softmax(-1)
    if not bool((values > 0).all()):
        raise FloatingPointError(
            "AdditiveLogRatioNormal draw underflowed the simplex interior"
        )
    return values

log_prob

log_prob(value)

Score an interior simplex event, including the ALR Jacobian.

PARAMETER DESCRIPTION
value

Candidate simplex events with the trailing component axis.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Gaussian log density minus the sum of log components; negative infinity outside the simplex interior.

RAISES DESCRIPTION
ValueError

If the event has the wrong number of components.

Source code in src/quivers/continuous/_additive_log_ratio.py
def log_prob(self, value):
    """Score an interior simplex event, including the ALR Jacobian.

    Parameters
    ----------
    value : Tensor
        Candidate simplex events with the trailing component axis.

    Returns
    -------
    Tensor
        Gaussian log density minus the sum of log components; negative
        infinity outside the simplex interior.

    Raises
    ------
    ValueError
        If the event has the wrong number of components.
    """
    value = torch.as_tensor(value, dtype=self.loc.dtype, device=self.loc.device)
    if value.ndim < 1 or value.shape[-1] != self.event_shape[0]:
        raise ValueError(
            "AdditiveLogRatioNormal event has the wrong component count"
        )
    value = value.expand(
        torch.broadcast_shapes(value.shape[:-1], self.batch_shape)
        + self.event_shape
    )
    valid = (
        torch.isfinite(value).all(-1)
        & (value > 0).all(-1)
        & constraints.simplex.check(value)
    )
    safe = torch.where(
        valid[..., None], value, torch.full_like(value, 1 / value.shape[-1])
    )
    log_y = safe.log()
    reference = self.reference.expand(log_y.shape[:-1]).unsqueeze(-1)
    ratios = log_y.gather(
        -1, self._coordinate_indices(log_y.shape[:-1])
    ) - log_y.gather(-1, reference)
    score = self._normal.log_prob(ratios) - log_y.sum(-1)
    return torch.where(valid, score, torch.full_like(score, -torch.inf))

Discrete Weibull counts

DiscreteWeibull(probs, concentration) has nonnegative integer support, with survival P(Y >= k) = probs**(k**concentration). The probability lies in [0, 1) and the concentration is positive; zero probability gives a point mass at zero. ConditionalDiscreteWeibull learns these native parameters, which are distinct from a response mean.

Parameters, scores, and moments use float64; samples use int64 and are non-reparameterized. Finite samples and finite requested quantiles above 2**53 are refused before integer conversion. Moment calculation uses adaptive sums with survival-integral remainder bounds. Native moment_rtol=1e-10 and moment_max_terms=262144 control its relative tolerance and count-term budget, retained by expand. A failure to certify the requested tolerance raises explicitly; mathematical moments still exist throughout the admitted parameter domain.

_discrete_weibull

Discrete Weibull counts with stable tails and bounded moment calculations.

DiscreteWeibull

DiscreteWeibull(probs, concentration, validate_args=None, *, moment_rtol=1e-10, moment_max_terms=262144)

Bases: Distribution

Counts with survival P(Y >= k) = probs**(k**concentration).

PARAMETER DESCRIPTION
probs

Survival parameter in [0, 1), with zero giving the point mass at zero.

TYPE: Tensor or float

concentration

Strictly positive power parameter.

TYPE: Tensor or float

validate_args

Whether to validate distribution parameters.

TYPE: bool or None DEFAULT: None

moment_rtol

Relative tolerance certified by omitted-moment integral bounds.

TYPE: float DEFAULT: 1e-10

moment_max_terms

Maximum number of count cells used for a moment calculation.

TYPE: int DEFAULT: 262144

Notes

Density and inverse-transform sampling require constant work per row. Moments use adaptive blocks and analytic upper bounds on the omitted tails. Failure to certify the requested tolerance raises explicitly. Native count arithmetic uses Float64 and integer samples use Int64.

Source code in src/quivers/continuous/_discrete_weibull.py
def __init__(
    self,
    probs,
    concentration,
    validate_args=None,
    *,
    moment_rtol=1e-10,
    moment_max_terms=262144,
):
    if (
        not 0 < moment_rtol < 1
        or not isinstance(moment_max_terms, int)
        or moment_max_terms < 1
    ):
        raise ValueError(
            "DiscreteWeibull moment tolerance must lie in (0,1) and term budget must be positive"
        )
    self.probs, self.concentration = _broadcast_count_parameters(
        probs, concentration
    )
    self.moment_rtol = moment_rtol
    self.moment_max_terms = moment_max_terms
    super().__init__(self.probs.shape, validate_args=validate_args)

mean property

mean

Compute the mean with an analytic omitted-tail error bound.

RETURNS DESCRIPTION
Tensor

Float64 response means within the configured relative tolerance.

variance property

variance

Compute variance without subtracting two large raw moments.

RETURNS DESCRIPTION
Tensor

Float64 variances within the configured relative tolerance.

expand

expand(batch_shape, _instance=None)

Expand the parameter views and retain the moment resource policy.

PARAMETER DESCRIPTION
batch_shape

Target batch dimensions.

TYPE: Size

_instance

Optional reusable instance.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
DiscreteWeibull

Expanded distribution.

Source code in src/quivers/continuous/_discrete_weibull.py
def expand(self, batch_shape, _instance=None):
    """Expand the parameter views and retain the moment resource policy.

    Parameters
    ----------
    batch_shape : torch.Size
        Target batch dimensions.
    _instance : Distribution or None
        Optional reusable instance.

    Returns
    -------
    DiscreteWeibull
        Expanded distribution.
    """
    new = self._get_checked_instance(DiscreteWeibull, _instance)
    shape = torch.Size(batch_shape)
    new.probs, new.concentration = (
        self.probs.expand(shape),
        self.concentration.expand(shape),
    )
    new.moment_rtol, new.moment_max_terms = self.moment_rtol, self.moment_max_terms
    super(DiscreteWeibull, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate a count mass in Float64.

PARAMETER DESCRIPTION
value

Candidate integer counts.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log mass, negative infinity outside the support.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_prob(self, value):
    """Evaluate a count mass in Float64.

    Parameters
    ----------
    value : Tensor
        Candidate integer counts.

    Returns
    -------
    Tensor
        Log mass, negative infinity outside the support.
    """
    _check_count_observation_source(value)
    return _log_mass(self.probs, self.concentration, value.double())

log_interval_mass

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

Evaluate an integer interval without subtracting rounded tail values.

PARAMETER DESCRIPTION
low

Real endpoints; None leaves a side unbounded.

TYPE: Tensor or float or None

high

Real endpoints; None leaves a side unbounded.

TYPE: Tensor or float or None

lower_closed

Endpoint membership, optionally varying across batch rows.

TYPE: bool or Tensor DEFAULT: True

upper_closed

Endpoint membership, optionally varying across batch rows.

TYPE: bool or Tensor DEFAULT: True

RETURNS DESCRIPTION
Tensor

Exact factored log probabilities on the distribution batch.

RAISES DESCRIPTION
ValueError

If an endpoint is NaN.

TypeError

If endpoint membership is not Boolean.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_interval_mass(self, low, high, *, lower_closed=True, upper_closed=True):
    """Evaluate an integer interval without subtracting rounded tail values.

    Parameters
    ----------
    low, high : Tensor or float or None
        Real endpoints; None leaves a side unbounded.
    lower_closed, upper_closed : bool or Tensor
        Endpoint membership, optionally varying across batch rows.

    Returns
    -------
    Tensor
        Exact factored log probabilities on the distribution batch.

    Raises
    ------
    ValueError
        If an endpoint is NaN.
    TypeError
        If endpoint membership is not Boolean.
    """
    from quivers.continuous._interval import _closed_flag

    lower_closed = _closed_flag(lower_closed, "lower_closed")
    upper_closed = _closed_flag(upper_closed, "upper_closed")
    lower = torch.as_tensor(
        -torch.inf if low is None else low,
        dtype=torch.float64,
        device=self.probs.device,
    )
    upper = torch.as_tensor(
        torch.inf if high is None else high,
        dtype=torch.float64,
        device=self.probs.device,
    )
    demand(
        ~torch.isnan(lower),
        lambda: ValueError("interval endpoints must not be NaN"),
    )
    demand(
        ~torch.isnan(upper),
        lambda: ValueError("interval endpoints must not be NaN"),
    )
    first = torch.where(
        torch.as_tensor(lower_closed, device=lower.device),
        lower.ceil(),
        lower.floor() + 1,
    ).clamp_min(0)
    last = torch.where(
        torch.as_tensor(upper_closed, device=upper.device),
        upper.floor(),
        upper.ceil() - 1,
    )
    valid = torch.isfinite(first) & (last >= first)
    first, last = torch.where(valid, first, 0.0), torch.where(valid, last, 0.0)
    mass = _integer_interval_log_mass(self.probs, self.concentration, first, last)
    return torch.where(valid, mass, -torch.inf)

log_cdf

log_cdf(value)

Evaluate probability at or below a real count bound in log space.

PARAMETER DESCRIPTION
value

Real count bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log cumulative probabilities.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_cdf(self, value):
    """Evaluate probability at or below a real count bound in log space.

    Parameters
    ----------
    value : Tensor
        Real count bounds.

    Returns
    -------
    Tensor
        Log cumulative probabilities.
    """
    return self._log_tails(value)[0]

log_survival_function

log_survival_function(value)

Evaluate probability strictly above a real count bound in log space.

PARAMETER DESCRIPTION
value

Real count bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log strict survival probabilities.

Source code in src/quivers/continuous/_discrete_weibull.py
def log_survival_function(self, value):
    """Evaluate probability strictly above a real count bound in log space.

    Parameters
    ----------
    value : Tensor
        Real count bounds.

    Returns
    -------
    Tensor
        Log strict survival probabilities.
    """
    return self._log_tails(value)[1]

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Real count bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Cumulative probabilities.

Source code in src/quivers/continuous/_discrete_weibull.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Real count bounds.

    Returns
    -------
    Tensor
        Cumulative probabilities.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Invert the staircase cumulative distribution.

PARAMETER DESCRIPTION
value

Probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Float64 count quantiles, positive infinity at probability one except for the degenerate-zero law.

RAISES DESCRIPTION
RuntimeError

If a finite requested quantile exceeds exact Float64 count capacity.

Source code in src/quivers/continuous/_discrete_weibull.py
def icdf(self, value):
    """Invert the staircase cumulative distribution.

    Parameters
    ----------
    value : Tensor
        Probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Float64 count quantiles, positive infinity at probability one
        except for the degenerate-zero law.

    Raises
    ------
    RuntimeError
        If a finite requested quantile exceeds exact Float64 count capacity.
    """
    value = value.double()
    if self._validate_args:
        _check_probability(value)
    interior = (value > 0) & (value < 1) & (self.probs > 0)
    probability = torch.where(interior, value, 0.5)
    q = torch.where(self.probs > 0, self.probs, 0.5)
    log_root = (
        (-torch.log1p(-probability)).log() - (-q.log()).log()
    ) / self.concentration
    root = log_root.exp()
    candidate = (root.ceil() - 1).clamp_min(0)
    _require_sample_capacity(torch.where(interior, candidate, 0.0))
    candidate = torch.where(
        self.cdf(candidate) < probability, candidate + 1, candidate
    )
    previous = (candidate - 1).clamp_min(0)
    candidate = torch.where(
        (candidate > 0) & (self.cdf(previous) >= probability), previous, candidate
    )
    result = torch.where(interior, candidate, 0.0)
    return torch.where((value == 1) & (self.probs > 0), torch.inf, result)

sample

sample(sample_shape=Size())

Draw integer counts by a vectorized exponential transform.

PARAMETER DESCRIPTION
sample_shape

Dimensions prepended to the parameter batch.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Int64 counts on the parameters' device.

RAISES DESCRIPTION
RuntimeError

If a generated count exceeds exact Float64 integer capacity.

Source code in src/quivers/continuous/_discrete_weibull.py
def sample(self, sample_shape=torch.Size()):
    """Draw integer counts by a vectorized exponential transform.

    Parameters
    ----------
    sample_shape : torch.Size
        Dimensions prepended to the parameter batch.

    Returns
    -------
    Tensor
        Int64 counts on the parameters' device.

    Raises
    ------
    RuntimeError
        If a generated count exceeds exact Float64 integer capacity.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        exponential = torch.empty(
            shape, dtype=self.probs.dtype, device=self.probs.device
        ).exponential_()
        q = torch.where(self.probs > 0, self.probs, 0.5)
        log_count = (exponential.log() - (-q.log()).log()) / self.concentration
        count = torch.where(self.probs > 0, log_count.exp().floor(), 0.0)
        return _require_sample_capacity(count).long()

Zero-inflated asymmetric Laplace responses

ZeroInflatedAsymmetricLaplace(zero_prob, loc, scale, quantile) has an exact atom at zero and a continuous asymmetric Laplace component. Its score at zero is log(zero_prob), independently of the component's density there. loc is the component's selected quantile, with positive scale and a quantile strictly between zero and one. Its CDF includes the atom at zero; strict survival excludes it there. The formal definition specifies the mixed dominating measure and response mean.

ConditionalZeroInflatedAsymmetricLaplace learns the native parameters. The mixture sampler selects its branch before drawing a continuous response and provides no pathwise sampling gradient. Native and checked-reference execution support this family and DiscreteWeibull; all 11 external renderers explicitly refuse both.

_zero_inflated_asymmetric_laplace

An exact zero atom combined with an asymmetric Laplace component.

ZeroInflatedAsymmetricLaplace

ZeroInflatedAsymmetricLaplace(zero_prob, loc, scale, quantile, validate_args=None)

Bases: Distribution

Structural zeros and a continuous asymmetric Laplace response.

PARAMETER DESCRIPTION
zero_prob

Probability of the atom at zero, including zero and one.

TYPE: Tensor or float

loc

Quantile location of the continuous component.

TYPE: Tensor or float

scale

Positive component scale in the check-loss parameterization.

TYPE: Tensor or float

quantile

Component quantile strictly between zero and one.

TYPE: Tensor or float

validate_args

Whether to validate distribution parameters.

TYPE: bool or None DEFAULT: None

Notes

Density is relative to the sum of a zero atom and Lebesgue measure: the continuous density does not contribute to the mass at zero. Sampling selects the mixture branch before sampling its component.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def __init__(self, zero_prob, loc, scale, quantile, validate_args=None):
    self.zero_prob, self.loc, self.scale, self.quantile = broadcast_all(
        zero_prob, loc, scale, quantile
    )
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Expected mixed response.

RETURNS DESCRIPTION
Tensor

Component mean multiplied by its mixture probability.

variance property

variance

Variance including uncertainty about the mixture branch.

RETURNS DESCRIPTION
Tensor

Component variance and between-component mean contribution.

expand

expand(batch_shape, _instance=None)

Expand parameter views over a new batch.

PARAMETER DESCRIPTION
batch_shape

Target broadcast batch dimensions.

TYPE: Size

_instance

Optional reusable distribution instance.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
ZeroInflatedAsymmetricLaplace

Distribution with expanded parameter views.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views over a new batch.

    Parameters
    ----------
    batch_shape : torch.Size
        Target broadcast batch dimensions.
    _instance : Distribution or None
        Optional reusable distribution instance.

    Returns
    -------
    ZeroInflatedAsymmetricLaplace
        Distribution with expanded parameter views.
    """
    new = self._get_checked_instance(ZeroInflatedAsymmetricLaplace, _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(ZeroInflatedAsymmetricLaplace, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate the zero atom or continuous component density.

PARAMETER DESCRIPTION
value

Real responses, broadcastable with the parameter batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log atom mass at zero and log Lebesgue density elsewhere.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def log_prob(self, value):
    """Evaluate the zero atom or continuous component density.

    Parameters
    ----------
    value : Tensor
        Real responses, broadcastable with the parameter batch.

    Returns
    -------
    Tensor
        Log atom mass at zero and log Lebesgue density elsewhere.
    """
    finite = torch.isfinite(value)
    atom = value == 0
    point = torch.where(finite, value, 0.0)
    probability = torch.where(atom & finite, self.zero_prob, 1.0)
    at_zero = probability.log()
    ordinary_probability = torch.where(~atom & finite, self.zero_prob, 0.0)
    ordinary = torch.log1p(-ordinary_probability) + self._component().log_prob(
        point
    )
    return torch.where(finite, torch.where(atom, at_zero, ordinary), -torch.inf)

log_cdf

log_cdf(value)

Evaluate log probability at or below a response.

PARAMETER DESCRIPTION
value

Real response bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log cumulative probabilities, including the atom at zero.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def log_cdf(self, value):
    """Evaluate log probability at or below a response.

    Parameters
    ----------
    value : Tensor
        Real response bounds.

    Returns
    -------
    Tensor
        Log cumulative probabilities, including the atom at zero.
    """
    return self._log_tails(value)[0]

log_survival_function

log_survival_function(value)

Evaluate log probability strictly above a response.

PARAMETER DESCRIPTION
value

Real response bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log survival probabilities, excluding the atom at zero.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def log_survival_function(self, value):
    """Evaluate log probability strictly above a response.

    Parameters
    ----------
    value : Tensor
        Real response bounds.

    Returns
    -------
    Tensor
        Log survival probabilities, excluding the atom at zero.
    """
    return self._log_tails(value)[1]

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Real response bounds.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Cumulative probabilities.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Real response bounds.

    Returns
    -------
    Tensor
        Cumulative probabilities.
    """
    return (1 - self.zero_prob) * self._component().cdf(value) + self.zero_prob * (
        value >= 0
    ).to(self.loc.dtype)

icdf

icdf(value)

Invert the continuous tails and the jump at zero.

PARAMETER DESCRIPTION
value

Probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Generalized quantiles, with zero throughout the atom's jump.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def icdf(self, value):
    """Invert the continuous tails and the jump at zero.

    Parameters
    ----------
    value : Tensor
        Probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Generalized quantiles, with zero throughout the atom's jump.
    """
    if self._validate_args:
        _check_probability(value)
    value, zero_prob = torch.broadcast_tensors(value, self.zero_prob)
    base = self._component()
    component_mass = 1 - zero_prob
    left = component_mass * base.cdf(torch.zeros_like(value))
    right = left + zero_prob
    atom = (value >= left) & (value <= right)
    degenerate = zero_prob == 1
    denominator = torch.where(degenerate, 1.0, component_mass)
    transformed = torch.where(value <= left, value, value - zero_prob) / denominator
    endpoint = (value == 0) | (value == 1)
    transformed = torch.where(atom | degenerate | endpoint, 0.5, transformed)
    result = torch.where(atom | degenerate, 0.0, base.icdf(transformed))
    result = torch.where((value == 0) & ~degenerate, -torch.inf, result)
    return torch.where((value == 1) & ~degenerate, torch.inf, result)

sample

sample(sample_shape=Size())

Select branches before sampling active continuous responses.

PARAMETER DESCRIPTION
sample_shape

Dimensions prepended to the parameter batch.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Floating responses, including exact structural zeros.

Source code in src/quivers/continuous/_zero_inflated_asymmetric_laplace.py
def sample(self, sample_shape=torch.Size()):
    """Select branches before sampling active continuous responses.

    Parameters
    ----------
    sample_shape : torch.Size
        Dimensions prepended to the parameter batch.

    Returns
    -------
    Tensor
        Floating responses, including exact structural zeros.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        active = torch.rand(
            shape, dtype=self.loc.dtype, device=self.loc.device
        ) >= self.zero_prob.expand(shape)
        result = torch.zeros(shape, dtype=self.loc.dtype, device=self.loc.device)
        if bool(active.any()):
            component = AsymmetricLaplace(
                self.loc.expand(shape)[active],
                self.scale.expand(shape)[active],
                self.quantile.expand(shape)[active],
                validate_args=False,
            )
            result[active] = component.sample()
        return result

Response-time distributions

ExGaussian(loc, scale, rate) is the sum of independent Normal and Exponential variables, with response mean loc + 1/rate. InverseGaussian(mu, shape) uses the response mean and positive shape directly. Both provide native densities, CDFs, moments, broadcasting, and reparameterized sampling. Inverse Gaussian samples use an exact vectorized transformation and implicit CDF derivatives; its discrete sampler branch is not differentiated as though it were fixed.

Both laws expose log_cdf and log_survival_function. These methods use Float64 arithmetic and retain the smaller tail before complementing it; cdf projects the result to the promoted parameter/query dtype. Interval normalization uses the paired tails once per endpoint. A positive local density rule handles narrow intervals whose endpoint tails round to the same number, including adjacent representable bounds.

The Gaussian divided-difference calculation checks agreement between fixed eight- and 32-node rules for short separations. Nonconvergence, a scaled argument magnitude above 1e150, or a separation above 1e150 raises RuntimeError; the scalar reference backend raises DistributionError. This is a bounded numerical algorithm, with no uniform accuracy guarantee across all parameter regimes. Finite log-tail and local-interval calculations support first and second parameter derivatives and forward automatic differentiation.

_response_time

Exponentially modified Gaussian and inverse Gaussian response distributions.

ExGaussian

ExGaussian(loc: Tensor | float, scale: Tensor | float, rate: Tensor | float, validate_args: bool | None = None)

Bases: Distribution

Sum of independent Normal and Exponential random variables.

PARAMETER DESCRIPTION
loc

Mean of the Normal component, distinct from the response mean.

TYPE: Tensor or float

scale

Strictly positive standard deviation of the Normal component.

TYPE: Tensor or float

rate

Strictly positive rate of the Exponential component.

TYPE: Tensor or float

validate_args

Whether to validate parameters and evaluation points.

TYPE: bool or None DEFAULT: None

Notes

The response mean is loc + 1/rate. The brms formula interface predicts that mean and calls the exponential mean beta.

Source code in src/quivers/continuous/_response_time.py
def __init__(
    self,
    loc: Tensor | float,
    scale: Tensor | float,
    rate: Tensor | float,
    validate_args: bool | None = None,
) -> None:
    self.loc, self.scale, self.rate = broadcast_all(loc, scale, rate)
    super().__init__(self.loc.shape, validate_args=validate_args)

log_cdf

log_cdf(value: Tensor) -> Tensor

Return log P(Y <= value), retaining small Gaussian-exponential tails.

PARAMETER DESCRIPTION
value

Extended-real evaluation points, broadcast with the batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log cumulative probabilities. Computed in Float64 to retain probabilities that ordinary CDF evaluation rounds away.

Source code in src/quivers/continuous/_response_time.py
def log_cdf(self, value: Tensor) -> Tensor:
    """Return log P(Y <= value), retaining small Gaussian-exponential tails.

    Parameters
    ----------
    value : Tensor
        Extended-real evaluation points, broadcast with the batch.

    Returns
    -------
    Tensor
        Log cumulative probabilities. Computed in Float64 to retain
        probabilities that ordinary CDF evaluation rounds away.
    """
    return self._log_tails(value)[0]

log_survival_function

log_survival_function(value: Tensor) -> Tensor

Return log P(Y > value), without subtracting a rounded CDF.

PARAMETER DESCRIPTION
value

Extended-real evaluation points, broadcast with the batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log strict upper-tail probabilities. Computed in Float64 to retain probabilities that ordinary CDF evaluation rounds away.

Source code in src/quivers/continuous/_response_time.py
def log_survival_function(self, value: Tensor) -> Tensor:
    """Return log P(Y > value), without subtracting a rounded CDF.

    Parameters
    ----------
    value : Tensor
        Extended-real evaluation points, broadcast with the batch.

    Returns
    -------
    Tensor
        Log strict upper-tail probabilities. Computed in Float64 to retain
        probabilities that ordinary CDF evaluation rounds away.
    """
    return self._log_tails(value)[1]

log_density_variation

log_density_variation(lower: Tensor, upper: Tensor) -> Tensor

Bound the absolute log-density change across a finite interval.

PARAMETER DESCRIPTION
lower

Finite interval endpoints, broadcast against the parameters.

TYPE: Tensor

upper

Finite interval endpoints, broadcast against the parameters.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A nonnegative Float64 variation bound, or infinity outside a finite positive-width interval. The inverse Mills ratio obeys m(t) <= max(-t, 0) + 1, yielding a conservative score bound.

Source code in src/quivers/continuous/_response_time.py
def log_density_variation(self, lower: Tensor, upper: Tensor) -> Tensor:
    """Bound the absolute log-density change across a finite interval.

    Parameters
    ----------
    lower, upper : Tensor
        Finite interval endpoints, broadcast against the parameters.

    Returns
    -------
    Tensor
        A nonnegative Float64 variation bound, or infinity outside a
        finite positive-width interval. The inverse Mills ratio obeys
        m(t) <= max(-t, 0) + 1, yielding a conservative score bound.
    """
    lower, upper = lower.double(), upper.double()
    valid = torch.isfinite(lower) & torch.isfinite(upper) & (upper > lower)
    start = torch.where(valid, lower, self.loc.double())
    width = torch.where(valid, upper - lower, 1.0)
    rate, scale = self.rate.double(), self.scale.double()
    t = (start - self.loc.double()) / scale - rate * scale
    bound = width * (rate + ((-t).clamp_min(0) + 1) / scale)
    return torch.where(valid, bound, torch.inf)

InverseGaussian

InverseGaussian(mu: Tensor | float, shape: Tensor | float, validate_args: bool | None = None)

Bases: Distribution

Inverse Gaussian distribution in mean/shape parameterization.

PARAMETER DESCRIPTION
mu

Strictly positive response mean.

TYPE: Tensor or float

shape

Strictly positive shape, conventionally lambda.

TYPE: Tensor or float

validate_args

Whether to validate parameters and evaluation points.

TYPE: bool or None DEFAULT: None

Notes

Sampling uses the exact Michael–Schucany–Haas transformation without rejection loops. Its gradients use implicit differentiation of the CDF, rather than differentiating the sampler's discrete branch choice. The gradient is -partial_theta CDF(y) / density(y); common exponential factors cancel analytically before numerical evaluation.

Source code in src/quivers/continuous/_response_time.py
def __init__(
    self,
    mu: Tensor | float,
    shape: Tensor | float,
    validate_args: bool | None = None,
) -> None:
    self.mu, self.shape = broadcast_all(mu, shape)
    super().__init__(self.mu.shape, validate_args=validate_args)

log_cdf

log_cdf(value: Tensor) -> Tensor

Return log P(Y <= value), retaining finite extreme-tail values.

PARAMETER DESCRIPTION
value

Extended-real evaluation points, broadcast with the batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log cumulative probabilities. Computed in Float64 to retain probabilities that ordinary CDF evaluation rounds away.

Source code in src/quivers/continuous/_response_time.py
def log_cdf(self, value: Tensor) -> Tensor:
    """Return log P(Y <= value), retaining finite extreme-tail values.

    Parameters
    ----------
    value : Tensor
        Extended-real evaluation points, broadcast with the batch.

    Returns
    -------
    Tensor
        Log cumulative probabilities. Computed in Float64 to retain
        probabilities that ordinary CDF evaluation rounds away.
    """
    return self._log_tails(value)[0]

log_survival_function

log_survival_function(value: Tensor) -> Tensor

Return log P(Y > value), retaining the Gaussian divided difference.

PARAMETER DESCRIPTION
value

Extended-real evaluation points, broadcast with the batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log strict upper-tail probabilities. Computed in Float64 to retain probabilities that ordinary CDF evaluation rounds away.

Source code in src/quivers/continuous/_response_time.py
def log_survival_function(self, value: Tensor) -> Tensor:
    """Return log P(Y > value), retaining the Gaussian divided difference.

    Parameters
    ----------
    value : Tensor
        Extended-real evaluation points, broadcast with the batch.

    Returns
    -------
    Tensor
        Log strict upper-tail probabilities. Computed in Float64 to retain
        probabilities that ordinary CDF evaluation rounds away.
    """
    return self._log_tails(value)[1]

log_density_variation

log_density_variation(lower: Tensor, upper: Tensor) -> Tensor

Bound the absolute log-density change over a positive interval.

PARAMETER DESCRIPTION
lower

Interval endpoints, broadcast against the parameters.

TYPE: Tensor

upper

Interval endpoints, broadcast against the parameters.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A nonnegative Float64 variation bound, or infinity outside finite strictly positive endpoints.

Source code in src/quivers/continuous/_response_time.py
def log_density_variation(self, lower: Tensor, upper: Tensor) -> Tensor:
    """Bound the absolute log-density change over a positive interval.

    Parameters
    ----------
    lower, upper : Tensor
        Interval endpoints, broadcast against the parameters.

    Returns
    -------
    Tensor
        A nonnegative Float64 variation bound, or infinity outside
        finite strictly positive endpoints.
    """
    lower, upper = lower.double(), upper.double()
    valid = (
        torch.isfinite(lower)
        & torch.isfinite(upper)
        & (lower > 0)
        & (upper > lower)
    )
    start = torch.where(valid, lower, self.mu.double())
    width = torch.where(valid, upper - lower, 1.0)
    mu, shape = self.mu.double(), self.shape.double()
    bound = width * (
        1.5 / start + 0.5 * (shape / start) / start + 0.5 * (shape / mu) / mu
    )
    return torch.where(valid, bound, torch.inf)

Skew, shifted, and extreme-value distributions

SkewNormal(loc, scale, skewness) uses the native Azzalini location/scale parameters. ShiftedLogNormal(loc, scale, shift) shifts a lognormal component by a nonnegative amount. Frechet(scale, concentration) has a positive concentration; GeneralizedExtremeValue(loc, scale, concentration) has a real one, with the Gumbel limit at zero. These scalar response laws have different moment domains and support endpoints; see the native-family guide. The formula interface performs its own response-parameter conversions.

The four native distributions provide cdf, log_cdf, log_survival_function, icdf, and direct vectorized pathwise samples. Their ConditionalSkewNormal, ConditionalShiftedLogNormal, ConditionalFrechet, and ConditionalGeneralizedExtremeValue wrappers learn the native constructor parameters. Checked-reference execution is supported; all 11 external renderers explicitly refuse these four laws. Skew-normal CDF and quantile evaluation uses float64 intermediate arithmetic and deterministic quadrature, with no uniform error guarantee. Those two methods require a device with float64 support.

_skew_normal

Skew-normal responses with stable positive-integral tail probabilities.

SkewNormal

SkewNormal(loc, scale, skewness, validate_args=None)

Bases: Distribution

Skew-normal law in Azzalini location, scale, and skewness parameters.

PARAMETER DESCRIPTION
loc

Location of the underlying skewed normal, distinct from its mean.

TYPE: Tensor or float

scale

Positive scale, distinct from its standard deviation.

TYPE: Tensor or float

skewness

Real Azzalini shape parameter, conventionally alpha.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_skew_normal.py
def __init__(self, loc, scale, skewness, validate_args=None):
    self.loc, self.scale, self.skewness = broadcast_all(loc, scale, skewness)
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(SkewNormal, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    finite = torch.isfinite(value)
    point = torch.where(finite, value, self.loc)
    z = (point - self.loc) / self.scale
    return torch.where(
        finite, _log_density(z, self.skewness) - self.scale.log(), -torch.inf
    )

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    finite = torch.isfinite(value)
    point = torch.where(finite, value, self.loc)
    z, alpha = torch.broadcast_tensors(
        (point - self.loc) / self.scale, self.skewness
    )
    output = _SkewLogCDF.apply(z.double(), alpha.double()).to(z.dtype)
    return torch.where(finite, output, torch.where(value > 0, 0.0, -torch.inf))

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    finite = torch.isfinite(value)
    point = torch.where(finite, value, self.loc)
    z, alpha = torch.broadcast_tensors(
        (self.loc - point) / self.scale, -self.skewness
    )
    output = _SkewLogCDF.apply(z.double(), alpha.double()).to(z.dtype)
    return torch.where(finite, output, torch.where(value > 0, -torch.inf, 0.0))

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    inside = (value > 0) & (value < 1)
    p, alpha = torch.broadcast_tensors(
        torch.where(inside, value, torch.full_like(value, 0.5)), self.skewness
    )
    z = _SkewQuantile.apply(p.double(), alpha.double()).to(p.dtype)
    result = self.loc + self.scale * z
    return torch.where(
        inside, result, torch.where(value == 0, -torch.inf, torch.inf)
    )

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_skew_normal.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    shape = self._extended_shape(sample_shape)
    first = torch.randn(shape, dtype=self.loc.dtype, device=self.loc.device)
    second = torch.randn_like(first)
    denominator = torch.hypot(self.skewness, torch.ones_like(self.skewness))
    return self.loc + self.scale * (
        (self.skewness / denominator) * first.abs() + second / denominator
    )

_shape_families

Shifted lognormal, Frechet, and generalized extreme-value response laws.

ShiftedLogNormal

ShiftedLogNormal(loc, scale, shift, validate_args=None)

Bases: Distribution

A lognormal response plus a nonnegative location shift.

PARAMETER DESCRIPTION
loc

Mean of the underlying normal log response.

TYPE: Tensor or float

scale

Positive standard deviation of the underlying normal.

TYPE: Tensor or float

shift

Nonnegative lower support endpoint.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_shape_families.py
def __init__(self, loc, scale, shift, validate_args=None):
    self.loc, self.scale, self.shift = broadcast_all(loc, scale, shift)
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

support

support()

Return the parameter-dependent response support.

RETURNS DESCRIPTION
Constraint

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
@constraints.dependent_property(is_discrete=False, event_dim=0)
def support(self):
    """Return the parameter-dependent response support.

    Returns
    -------
    constraints.Constraint
        Broadcast result with the parameter device and dtype.
    """
    return constraints.greater_than(self.shift)

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(ShiftedLogNormal, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    _, inside, z, safe = self._standardized(value)
    result = (
        -0.5 * z.square() - self.scale.log() - safe.log() - 0.91893853320467274178
    )
    return torch.where(inside, result, -torch.inf)

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    difference, inside, z, _ = self._standardized(value)
    return torch.where(
        inside,
        torch.special.log_ndtr(z),
        torch.where(difference > 0, 0.0, -torch.inf),
    )

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    difference, inside, z, _ = self._standardized(value)
    return torch.where(
        inside,
        torch.special.log_ndtr(-z),
        torch.where(difference > 0, -torch.inf, 0.0),
    )

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    return self.shift + torch.exp(
        self.loc + self.scale * torch.special.ndtri(value)
    )

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z = torch.randn(
        self._extended_shape(sample_shape),
        dtype=self.loc.dtype,
        device=self.loc.device,
    )
    return self.shift + torch.exp(self.loc + self.scale * z)

Frechet

Frechet(scale, concentration, validate_args=None)

Bases: Distribution

Frechet distribution on positive responses.

PARAMETER DESCRIPTION
scale

Positive response scale.

TYPE: Tensor or float

concentration

Positive tail shape. The first moment exists above one and the second moment above two.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_shape_families.py
def __init__(self, scale, concentration, validate_args=None):
    self.scale, self.concentration = broadcast_all(scale, concentration)
    super().__init__(self.scale.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    new.scale, new.concentration = (
        self.scale.expand(shape),
        self.concentration.expand(shape),
    )
    super(Frechet, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    inside, ratio = self._log_ratio(value)
    a = self.concentration
    result = a.log() - self.scale.log() - (a + 1) * ratio - torch.exp(-a * ratio)
    return torch.where(inside, result, -torch.inf)

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    inside, ratio = self._log_ratio(value)
    result = -torch.exp(-self.concentration * ratio)
    return torch.where(inside, result, torch.where(value > 0, 0.0, -torch.inf))

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    inside, ratio = self._log_ratio(value)
    log_t = -self.concentration * ratio
    result = _log1mexp_neg_exp(log_t)
    return torch.where(inside, result, torch.where(value > 0, -torch.inf, 0.0))

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    return self.scale * torch.exp(-torch.log(-value.log()) / self.concentration)

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    exponential = torch.empty(
        self._extended_shape(sample_shape),
        dtype=self.scale.dtype,
        device=self.scale.device,
    ).exponential_()
    return self.scale * torch.exp(-exponential.log() / self.concentration)

GeneralizedExtremeValue

GeneralizedExtremeValue(loc, scale, concentration, validate_args=None)

Bases: Distribution

Generalized extreme-value law with a differentiable Gumbel limit.

PARAMETER DESCRIPTION
loc

Response location, distinct from the expectation.

TYPE: Tensor or float

scale

Positive scale.

TYPE: Tensor or float

concentration

Real extreme-value shape; zero gives Gumbel. SciPy's genextreme uses the opposite sign for its shape parameter.

TYPE: Tensor or float

validate_args

Whether to validate parameters.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_shape_families.py
def __init__(self, loc, scale, concentration, validate_args=None):
    self.loc, self.scale, self.concentration = broadcast_all(
        loc, scale, concentration
    )
    super().__init__(self.loc.shape, validate_args=validate_args)

mean property

mean

Return the response expectation, or infinity when its first moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

variance property

variance

Return the response variance, or infinity when its second moment does not exist.

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

support

support()

Return the parameter-dependent response support.

RETURNS DESCRIPTION
Constraint

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
@constraints.dependent_property(is_discrete=False, event_dim=0)
def support(self):
    """Return the parameter-dependent response support.

    Returns
    -------
    constraints.Constraint
        Broadcast result with the parameter device and dtype.
    """
    c = self.concentration
    safe = torch.where(c != 0, c, torch.ones_like(c))
    endpoint = self.loc - self.scale / safe
    return constraints.interval(
        torch.where(c > 0, endpoint, -torch.inf),
        torch.where(c < 0, endpoint, torch.inf),
    )

expand

expand(batch_shape, _instance=None)

Expand parameter views without copying their underlying storage.

PARAMETER DESCRIPTION
batch_shape

Requested broadcast batch dimensions.

TYPE: Size or Sequence[int]

_instance

Optional instance supplied by PyTorch.

TYPE: Distribution or None DEFAULT: None

RETURNS DESCRIPTION
Distribution

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def expand(self, batch_shape, _instance=None):
    """Expand parameter views without copying their underlying storage.

    Parameters
    ----------
    batch_shape : torch.Size or Sequence[int]
        Requested broadcast batch dimensions.
    _instance : Distribution or None
        Optional instance supplied by PyTorch.

    Returns
    -------
    Distribution
        Broadcast result with the parameter device and dtype.
    """
    new = self._get_checked_instance(type(self), _instance)
    shape = torch.Size(batch_shape)
    for name in self.arg_constraints:
        setattr(new, name, getattr(self, name).expand(shape))
    super(GeneralizedExtremeValue, new).__init__(shape, validate_args=False)
    new._validate_args = self._validate_args
    return new

log_prob

log_prob(value)

Evaluate log densities, returning negative infinity outside the support.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_prob(self, value):
    """Evaluate log densities, returning negative infinity outside the support.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z, inside, r = self._transformed(value)
    result = -self.scale.log() - (1 + self.concentration) * r - torch.exp(-r)
    endpoint = (self.concentration < 0) & (1 + self.concentration * z == 0)
    limit = torch.where(
        self.concentration == -1,
        -self.scale.log(),
        torch.where(self.concentration < -1, torch.inf, -torch.inf),
    )
    return torch.where(inside, result, torch.where(endpoint, limit, -torch.inf))

log_cdf

log_cdf(value)

Evaluate cumulative probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_cdf(self, value):
    """Evaluate cumulative probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z, inside, r = self._transformed(value)
    result = -torch.exp(-r)
    upper = (self.concentration < 0) & (1 + self.concentration * z <= 0) | (
        z == torch.inf
    )
    return torch.where(inside, result, torch.where(upper, 0.0, -torch.inf))

log_survival_function

log_survival_function(value)

Evaluate complementary probabilities directly in log space.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def log_survival_function(self, value):
    """Evaluate complementary probabilities directly in log space.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    z, inside, r = self._transformed(value)
    result = _log1mexp_neg_exp(-r)
    upper = (self.concentration < 0) & (1 + self.concentration * z <= 0) | (
        z == torch.inf
    )
    return torch.where(inside, result, torch.where(upper, -torch.inf, 0.0))

cdf

cdf(value)

Evaluate cumulative probabilities.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def cdf(self, value):
    """Evaluate cumulative probabilities.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    return self.log_cdf(value).exp()

icdf

icdf(value)

Transform probabilities to response quantiles.

PARAMETER DESCRIPTION
value

Response values; for icdf, probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def icdf(self, value):
    """Transform probabilities to response quantiles.

    Parameters
    ----------
    value : Tensor
        Response values; for icdf, probabilities in the closed unit interval.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    if self._validate_args:
        _check_probability(value)
    interior = (value > 0) & (value < 1)
    p = torch.where(interior, value, torch.full_like(value, 0.5))
    gumbel = -torch.log(-p.log())
    result = self.loc + self.scale * gumbel * _expm1_ratio(
        self.concentration * gumbel
    )
    safe = torch.where(
        self.concentration != 0,
        self.concentration,
        torch.ones_like(self.concentration),
    )
    endpoint = self.loc - self.scale / safe
    lower = torch.where(self.concentration > 0, endpoint, -torch.inf)
    upper = torch.where(self.concentration < 0, endpoint, torch.inf)
    return torch.where(interior, result, torch.where(value == 0, lower, upper))

rsample

rsample(sample_shape=Size())

Draw responses with pathwise gradients through the distribution parameters.

PARAMETER DESCRIPTION
sample_shape

Leading sample dimensions.

TYPE: Size or Sequence[int] DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Broadcast result with the parameter device and dtype.

Source code in src/quivers/continuous/_shape_families.py
def rsample(self, sample_shape=torch.Size()):
    """Draw responses with pathwise gradients through the distribution parameters.

    Parameters
    ----------
    sample_shape : torch.Size or Sequence[int]
        Leading sample dimensions.

    Returns
    -------
    Tensor
        Broadcast result with the parameter device and dtype.
    """
    exponential = torch.empty(
        self._extended_shape(sample_shape),
        dtype=self.loc.dtype,
        device=self.loc.device,
    ).exponential_()
    gumbel = -exponential.log()
    return self.loc + self.scale * gumbel * _expm1_ratio(
        self.concentration * gumbel
    )

Truncating conditional families

Truncated denotes a normalized restriction of the base conditional distribution. For independent scalar coordinates, it sums each coordinate's log interval mass; a coupled event requires a joint rectangle-mass operation. The formal definition distinguishes this conditioning from interval censoring.

The wrapper reads the base distribution through _get_dist(x) and uses deterministic CDF or log-tail interval masses. Normal tails have a stable specialized calculation; Gamma and Poisson use incomplete-gamma probabilities. Unsupported base/event contracts and zero or nonfinite computed interval masses raise explicit errors. Normal sampling uses a stable inverse CDF; other bases use bounded rejection controlled by max_rejection_iterations. The rejection branch does not establish a general pathwise derivative through the acceptance event.

Gamma interval masses use float64 lower-tail series, upper-tail continued fractions, and small-shape complement calculations. Shape and rate derivatives propagate through converged recurrences; nonconvergence within 512 iterations raises explicitly. These numerical and derivative contracts do not assert a uniform accuracy or convergence guarantee.

Generalized Pareto tails

ConditionalGeneralizedPareto learns loc, positive scale, and real concentration, the tail index. The registered GeneralizedPareto family supports native and QIEC reference execution, with density, CDF, inverse CDF, and reparameterized draws. Its finite endpoint for negative indices and its exponential limit at zero are described in the tail-family guide. The native distribution implementation is private; the public API is the conditional wrapper and its registered FamilySpec.

Positive hurdle distributions

HurdleGamma(zero_prob, concentration, rate) and HurdleLogNormal(zero_prob, loc, scale) combine an exact zero atom with a strictly positive component. ConditionalHurdleGamma and ConditionalHurdleLogNormal learn those parameters from their input. Both native distributions provide log mass at zero, positive-response log density, CDF, response mean/variance, broadcasting, and sampling. The structural zero gate makes sampling non-reparameterized. Their scoring and moment parameters remain differentiable, including finite permitted-event gradients at zero probabilities of zero and one. The Gamma CDF inherits PyTorch's incomplete-gamma derivative limitations for its concentration parameter.

_positive_hurdle

Exact zero atoms combined with strictly positive response distributions.

HurdleGamma

HurdleGamma(zero_prob: Tensor | float, concentration: Tensor | float, rate: Tensor | float, validate_args: bool | None = None)

Bases: _PositiveHurdle

A zero atom and Gamma concentration/rate response component.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability, including zero and one.

TYPE: Tensor or float

concentration

Positive Gamma shape.

TYPE: Tensor or float

rate

Positive Gamma rate.

TYPE: Tensor or float

validate_args

Whether to validate parameters and scored observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_positive_hurdle.py
def __init__(
    self,
    zero_prob: Tensor | float,
    concentration: Tensor | float,
    rate: Tensor | float,
    validate_args: bool | None = None,
) -> None:
    self.zero_prob, self.concentration, self.rate = broadcast_all(
        zero_prob, concentration, rate
    )
    super().__init__(self.zero_prob.shape, validate_args=validate_args)

HurdleLogNormal

HurdleLogNormal(zero_prob: Tensor | float, loc: Tensor | float, scale: Tensor | float, validate_args: bool | None = None)

Bases: _PositiveHurdle

A zero atom and LogNormal log-location/log-scale response component.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability, including zero and one.

TYPE: Tensor or float

loc

Mean of the underlying Normal log response.

TYPE: Tensor or float

scale

Positive standard deviation of the underlying Normal log response.

TYPE: Tensor or float

validate_args

Whether to validate parameters and scored observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_positive_hurdle.py
def __init__(
    self,
    zero_prob: Tensor | float,
    loc: Tensor | float,
    scale: Tensor | float,
    validate_args: bool | None = None,
) -> None:
    self.zero_prob, self.loc, self.scale = broadcast_all(zero_prob, loc, scale)
    super().__init__(self.zero_prob.shape, validate_args=validate_args)

Zero-inflated and hurdle counts

ZeroInflatedNegativeBinomial(zero_prob, total_count, probs), ZeroInflatedBinomial(zero_prob, total_count, probs), and ZeroInflatedBetaBinomial(zero_prob, total_count, concentration1, concentration0) add a structural zero to their count component. Their total zero probability includes both that atom and the component's own zero mass. HurdleNegativeBinomial(zero_prob, total_count, probs) instead assigns the whole zero probability to the atom and normalizes its component over positive counts. Negative-binomial probs follows PyTorch's convention; its component mean is total_count * probs / (1-probs).

These scalar count distributions provide differentiable log masses and moments, batch broadcasting, and non-reparameterized sampling. Binomial trial counts may be zero, giving a point mass at zero. At negative-binomial probs=0, the hurdle's positive component uses its limiting point mass at one. Its sampler uses a compound-Poisson representation with logarithmic counts, avoiding rejection from an almost-always-zero count distribution. The count guide relates these native parameters to regression means, precision, and links. Native and QIEC reference execution support all four. Each of the 11 external renderers refuses them with a family:<Family> diagnostic; native registration alone does not provide a target mapping.

Native Binomial, BetaBinomial, NegativeBinomial, Poisson, and these four count mixtures compute parameters, log scores, and mean/variance in float64. Promotion preserves gradients to learned float32 parameter heads, whose gradients retain their original dtype. Finite trial counts must satisfy 0 <= total_count <= 2**53 before conversion, preserving exact integer representation; the general Int carrier remains signed 64-bit. Large counts should arrive as integer arrays or integer literals, since promotion cannot recover a value already rounded in float32. Discrete samples remain integer-valued and non-reparameterized. Arithmetic count observations are checked before conversion as well: a finite original value outside [-2**53, 2**53] is refused. With argument validation disabled, fractional, nonfinite, or other off-support values return negative infinity rather than being truncated. Finite category indices retain their separate support contract without imposing the arithmetic-count bound. The count density kernels use stable deviance, Stirling, and gamma-increment formulas where applicable; this precision policy does not assert a uniform numerical error bound over all parameter regimes.

For Poisson, negative-binomial, and their inflated or hurdle samplers, nonfinite generated intensities or counts, or values above 2**53, raise RuntimeError natively and DistributionError in the reference backend. No truncation, renormalization, or overflow-hiding redraw is performed. Structural-zero outcomes skip the unreachable count branch. See the count guide for the distinction between sampling limits and density evaluation.

_zero_inflated_count

Zero atoms combined with normalized binomial and negative-binomial counts.

BetaBinomial

BetaBinomial(total_count, concentration1, concentration0, validate_args=None)

Bases: _CountCDF, Distribution

A broadcast beta-binomial component, including zero trials.

PARAMETER DESCRIPTION
total_count

Nonnegative integer trial count.

TYPE: Tensor or int

concentration1

Positive success concentration.

TYPE: Tensor or float

concentration0

Positive failure concentration.

TYPE: Tensor or float

validate_args

Whether to validate arguments.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(self, total_count, concentration1, concentration0, validate_args=None):
    _check_trial_count_source(total_count)
    self.total_count, self.concentration1, self.concentration0 = (
        _broadcast_count_parameters(total_count, concentration1, concentration0)
    )
    demand(
        torch.isfinite(self.concentration1)
        & (self.concentration1 > 0)
        & torch.isfinite(self.concentration0)
        & (self.concentration0 > 0)
        & torch.isfinite(self.concentration1 + self.concentration0),
        lambda: ValueError(
            "beta-binomial concentrations and their sum must be finite"
        ),
    )
    super().__init__(self.total_count.shape, validate_args=validate_args)

mean property

mean: Tensor

Expected successes.

RETURNS DESCRIPTION
Tensor

Trial count times the beta mean.

variance property

variance: Tensor

Variance after integrating over the beta probability.

RETURNS DESCRIPTION
Tensor

Beta-binomial response variance.

log_prob

log_prob(value: Tensor) -> Tensor

Evaluate the finite count mass in the parameter dtype.

PARAMETER DESCRIPTION
value

Counts broadcastable with the parameter batch.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log mass, negative infinity outside the trial support.

Source code in src/quivers/continuous/_zero_inflated_count.py
def log_prob(self, value: Tensor) -> Tensor:
    """Evaluate the finite count mass in the parameter dtype.

    Parameters
    ----------
    value : Tensor
        Counts broadcastable with the parameter batch.

    Returns
    -------
    Tensor
        Log mass, negative infinity outside the trial support.
    """
    _check_count_observation_source(value)
    n, a, b, value = torch.broadcast_tensors(
        self.total_count,
        self.concentration1,
        self.concentration0,
        value.to(self.concentration1.dtype),
    )
    valid = constraints.nonnegative_integer.check(value) & (value <= n)
    k = torch.where(valid, value, 0.0)
    result = _beta_binomial_log_mass(k, torch.where(valid, n, 0.0), a, b)
    return torch.where(valid, result, -torch.inf)

sample

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

Draw a beta probability followed by a binomial count.

PARAMETER DESCRIPTION
sample_shape

Sample dimensions prepended to the batch.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Nonnegative integer counts.

Source code in src/quivers/continuous/_zero_inflated_count.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draw a beta probability followed by a binomial count.

    Parameters
    ----------
    sample_shape : torch.Size
        Sample dimensions prepended to the batch.

    Returns
    -------
    Tensor
        Nonnegative integer counts.
    """
    shape = sample_shape + self.batch_shape
    n = self.total_count.expand(shape)
    result = torch.zeros(shape, dtype=torch.int64, device=n.device)
    active = n > 0
    if bool(active.any()):
        concentrations = torch.stack(
            (self.concentration1, self.concentration0), -1
        ).expand(shape + (2,))[active]
        probability = _dirichlet_weights(concentrations)[..., 0]
        result[active] = (
            ClosedBinomial(n[active], probs=probability).sample().long()
        )
    return result

ZeroInflatedNegativeBinomial

ZeroInflatedNegativeBinomial(zero_prob, total_count, probs, validate_args=None)

Bases: _InflatedCount

Structural zeros plus NB successes before total_count failures.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability in [0, 1].

TYPE: Tensor or float

total_count

Nonnegative negative-binomial shape.

TYPE: Tensor or float

probs

Success probability in [0, 1), with count mean r*p/(1-p).

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(self, zero_prob, total_count, probs, validate_args=None):
    self.zero_prob, self.total_count, self.probs = _broadcast_count_parameters(
        zero_prob, total_count, probs
    )
    super().__init__(self.zero_prob.shape, validate_args=validate_args)

mean property

mean: Tensor

Expected count with an exact zero-probability endpoint.

RETURNS DESCRIPTION
Tensor

Mixture probability times r*p/(1-p).

variance property

variance: Tensor

Variance in the original probability parameterization.

RETURNS DESCRIPTION
Tensor

Within-count variance plus structural-zero variation.

ZeroInflatedBinomial

ZeroInflatedBinomial(zero_prob, total_count, probs, validate_args=None)

Bases: _InflatedCount

Structural zeros plus a binomial, including zero trials.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability in [0, 1].

TYPE: Tensor or float

total_count

Nonnegative integer trial counts.

TYPE: Tensor or int

probs

Binomial success probability in [0, 1].

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(self, zero_prob, total_count, probs, validate_args=None):
    _check_trial_count_source(total_count)
    self.zero_prob, self.total_count, self.probs = _broadcast_count_parameters(
        zero_prob, total_count, probs
    )
    super().__init__(self.zero_prob.shape, validate_args=validate_args)

support

support()

Counts between zero and the trial count.

RETURNS DESCRIPTION
Constraint

The parameter-dependent integer support.

Source code in src/quivers/continuous/_zero_inflated_count.py
@constraints.dependent_property(is_discrete=True, event_dim=0)
def support(self):
    """Counts between zero and the trial count.

    Returns
    -------
    constraints.Constraint
        The parameter-dependent integer support.
    """
    return constraints.integer_interval(0, self.total_count)

ZeroInflatedBetaBinomial

ZeroInflatedBetaBinomial(zero_prob, total_count, concentration1, concentration0, validate_args=None)

Bases: ZeroInflatedBinomial

Structural zeros plus a beta-binomial with integrated success probability.

PARAMETER DESCRIPTION
zero_prob

Structural zero probability in [0, 1].

TYPE: Tensor or float

total_count

Nonnegative integer trial counts.

TYPE: Tensor or int

concentration1

Positive beta success concentration.

TYPE: Tensor or float

concentration0

Positive beta failure concentration.

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(
    self, zero_prob, total_count, concentration1, concentration0, validate_args=None
):
    _check_trial_count_source(total_count)
    self.zero_prob, self.total_count, self.concentration1, self.concentration0 = (
        _broadcast_count_parameters(
            zero_prob, total_count, concentration1, concentration0
        )
    )
    Distribution.__init__(self, self.zero_prob.shape, validate_args=validate_args)

HurdleNegativeBinomial

HurdleNegativeBinomial(zero_prob, total_count, probs, validate_args=None)

Bases: ZeroInflatedNegativeBinomial

Zero atom plus a normalized strictly positive negative binomial.

PARAMETER DESCRIPTION
zero_prob

Hurdle probability in [0, 1].

TYPE: Tensor or float

total_count

Strictly positive negative-binomial shape.

TYPE: Tensor or float

probs

Success probability in [0, 1). At zero the positive component is its point-mass-at-one limit.

TYPE: Tensor or float

validate_args

Whether to validate parameters and observations.

TYPE: bool or None DEFAULT: None

Source code in src/quivers/continuous/_zero_inflated_count.py
def __init__(self, zero_prob, total_count, probs, validate_args=None):
    super().__init__(zero_prob, total_count, probs, validate_args=validate_args)

mean property

mean: Tensor

Expected hurdle count.

RETURNS DESCRIPTION
Tensor

Positive conditional mean times the nonzero probability.

variance property

variance: Tensor

Variance of the full hurdle response.

RETURNS DESCRIPTION
Tensor

Second moment minus the squared full mean.

log_prob

log_prob(value: Tensor) -> Tensor

Score the atom or normalized positive component without p=0 divisions.

PARAMETER DESCRIPTION
value

Nonnegative integer counts.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Exact log probabilities including the p=0 limit.

Source code in src/quivers/continuous/_zero_inflated_count.py
def log_prob(self, value: Tensor) -> Tensor:
    """Score the atom or normalized positive component without p=0 divisions.

    Parameters
    ----------
    value : Tensor
        Nonnegative integer counts.

    Returns
    -------
    Tensor
        Exact log probabilities including the p=0 limit.
    """
    _check_count_observation_source(value)
    if self._validate_args:
        self._validate_sample(value)
    valid = self.support.check(value)
    point = torch.where(valid & (value > 0), value, 1).to(self.probs.dtype)
    positive = (
        _log_gamma_increment(self.total_count + 1, point - 1)
        - torch.lgamma(point + 1)
        + _count_log(point - 1, self.probs)
        + self.total_count * torch.log1p(-self.probs)
        + self._positive_log_ratio()
    )
    rate = -self.total_count * torch.log1p(-self.probs)
    ordinary = rate > 1e-4
    safe_p = torch.where(ordinary, self.probs, torch.full_like(self.probs, 0.5))
    safe_r = torch.where(
        ordinary, self.total_count, torch.ones_like(self.total_count)
    )
    stable = _negative_binomial_log_mass(
        point, safe_r, safe_p.log(), torch.log1p(-safe_p)
    )
    stable = stable - torch.log(-torch.expm1(safe_r * torch.log1p(-safe_p)))
    positive = torch.where(ordinary, stable, positive)
    atom_probability = torch.where(valid & (value == 0), self.zero_prob, 1.0)
    positive_probability = torch.where(valid & (value > 0), self.zero_prob, 0.0)
    result = torch.where(
        value == 0,
        atom_probability.log(),
        torch.log1p(-positive_probability) + positive,
    )
    return torch.where(valid, result, -torch.inf)

sample

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

Draw structural zeros and efficiently conditioned positive NB counts.

PARAMETER DESCRIPTION
sample_shape

Dimensions prepended to the batch shape.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Nonnegative integer draws without reparameterized gradients.

Source code in src/quivers/continuous/_zero_inflated_count.py
def sample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draw structural zeros and efficiently conditioned positive NB counts.

    Parameters
    ----------
    sample_shape : torch.Size
        Dimensions prepended to the batch shape.

    Returns
    -------
    Tensor
        Nonnegative integer draws without reparameterized gradients.
    """
    with torch.no_grad():
        shape = self._extended_shape(sample_shape)
        active = torch.rand(
            shape, dtype=self.zero_prob.dtype, device=self.zero_prob.device
        ) >= self.zero_prob.expand(shape)
        result = torch.zeros(shape, dtype=torch.long, device=self.zero_prob.device)
        if active.any():
            result[active] = _positive_negative_binomial_sample(
                self.total_count.expand(shape)[active],
                self.probs.expand(shape)[active],
            )
        return result

Multivariate Student events

The Gaussian scale matrix is distinct from the Student response covariance. See the multivariate Student guide for event axes, moment boundaries, and constructor alternatives.

MultivariateStudentT

MultivariateStudentT(df: Tensor | float, loc: Tensor, covariance_matrix: Tensor | None = None, precision_matrix: Tensor | None = None, scale_tril: Tensor | None = None, validate_args: bool | None = None)

Bases: Distribution

A multivariate Student law with one shared radial scale per vector.

PARAMETER DESCRIPTION
df

Positive degrees of freedom, broadcast over Gaussian batch axes.

TYPE: Tensor or float

loc

Location with trailing event dimension D.

TYPE: Tensor

covariance_matrix

Exactly one Gaussian scale representation. The scale matrix is not the response covariance; the latter is df/(df-2) times the scale when df > 2. Factors follow MultivariateNormal conventions.

TYPE: Tensor or None DEFAULT: None

precision_matrix

Exactly one Gaussian scale representation. The scale matrix is not the response covariance; the latter is df/(df-2) times the scale when df > 2. Factors follow MultivariateNormal conventions.

TYPE: Tensor or None DEFAULT: None

scale_tril

Exactly one Gaussian scale representation. The scale matrix is not the response covariance; the latter is df/(df-2) times the scale when df > 2. Factors follow MultivariateNormal conventions.

TYPE: Tensor or None DEFAULT: None

validate_args

Torch argument and observation validation policy.

TYPE: bool or None DEFAULT: None

Notes

A single chi-squared variate scales every coordinate in each vector. Independent univariate Student distributions have a different joint law. The location is the response mean only for degrees of freedom above one.

Source code in src/quivers/continuous/_multivariate_student_t.py
def __init__(
    self,
    df: Tensor | float,
    loc: Tensor,
    covariance_matrix: Tensor | None = None,
    precision_matrix: Tensor | None = None,
    scale_tril: Tensor | None = None,
    validate_args: bool | None = None,
) -> None:
    df = torch.as_tensor(
        df,
        device=loc.device,
        dtype=None if isinstance(df, Tensor) else loc.dtype,
    )
    dtype = torch.promote_types(df.dtype, loc.dtype)
    for value in (covariance_matrix, precision_matrix, scale_tril):
        if value is not None:
            dtype = torch.promote_types(dtype, value.dtype)
    if not dtype.is_floating_point:
        dtype = torch.get_default_dtype()
    normal = MultivariateNormal(
        loc.to(dtype),
        covariance_matrix=None
        if covariance_matrix is None
        else covariance_matrix.to(dtype),
        precision_matrix=None
        if precision_matrix is None
        else precision_matrix.to(dtype),
        scale_tril=None if scale_tril is None else scale_tril.to(dtype),
        validate_args=validate_args,
    )
    batch = torch.broadcast_shapes(df.shape, normal.batch_shape)
    self._normal = normal.expand(batch)
    self.df = df.to(dtype).expand(batch)
    self.loc = self._normal.loc
    self.scale_tril = self._normal.scale_tril
    super().__init__(batch, normal.event_shape, validate_args=validate_args)

arg_constraints property

arg_constraints: dict[str, Constraint]

Read the checked heads without materializing covariance properties.

RETURNS DESCRIPTION
dict[str, Constraint]

Actual stored Gaussian factor and Student head constraints.

covariance_matrix property

covariance_matrix: Tensor

Return the Gaussian scale matrix, following Torch parameter names.

RETURNS DESCRIPTION
Tensor

Scale matrices with trailing shape (D,D).

precision_matrix property

precision_matrix: Tensor

Return the inverse Gaussian scale matrix.

RETURNS DESCRIPTION
Tensor

Inverse scale matrices with trailing shape (D,D).

mean property

mean: Tensor

Return the finite response mean where it exists.

RETURNS DESCRIPTION
Tensor

Location for df > 1 and NaN otherwise.

variance property

variance: Tensor

Return marginal variances with Student moment existence boundaries.

RETURNS DESCRIPTION
Tensor

Finite variances above two degrees of freedom, infinity between one and two, and NaN at or below one.

log_prob

log_prob(value: Tensor) -> Tensor

Evaluate the marginal vector density without auxiliary latent sites.

PARAMETER DESCRIPTION
value

Observations ending in the declared vector event axis.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One log density per sample and batch coordinate.

Source code in src/quivers/continuous/_multivariate_student_t.py
def log_prob(self, value: Tensor) -> Tensor:
    """Evaluate the marginal vector density without auxiliary latent sites.

    Parameters
    ----------
    value : Tensor
        Observations ending in the declared vector event axis.

    Returns
    -------
    Tensor
        One log density per sample and batch coordinate.
    """
    if self._validate_args:
        self._validate_sample(value)
    width = self.event_shape[0]
    factor = self._normal._unbroadcasted_scale_tril
    squared = _batch_mahalanobis(factor, value - self.loc)
    log_det = factor.diagonal(dim1=-2, dim2=-1).log().sum(-1)
    half = self.df / 2
    increment = torch.full_like(half, width / 2)
    return (
        _log_gamma_increment(half, increment)
        - (width / 2) * (self.df.log() + math.log(math.pi))
        - log_det
        - ((self.df + width) / 2) * torch.log1p(squared / self.df)
    )

rsample

rsample(sample_shape: Sequence[int] = Size()) -> Tensor

Draw pathwise using one radial chi-squared scale per vector.

PARAMETER DESCRIPTION
sample_shape

Leading sample axes.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Draws with sample, batch, and final vector event dimensions.

Source code in src/quivers/continuous/_multivariate_student_t.py
def rsample(self, sample_shape: Sequence[int] = torch.Size()) -> Tensor:
    """Draw pathwise using one radial chi-squared scale per vector.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading sample axes.

    Returns
    -------
    Tensor
        Draws with sample, batch, and final vector event dimensions.
    """
    normal = self._normal.rsample(torch.Size(sample_shape))
    radial = Chi2(self.df).rsample(torch.Size(sample_shape))
    return self.loc + (normal - self.loc) * torch.sqrt(self.df / radial)[..., None]

expand

expand(batch_shape: Sequence[int], _instance=None) -> MultivariateStudentT

Expand only batch axes while retaining the shared factor.

PARAMETER DESCRIPTION
batch_shape

Broadcast-compatible new batch dimensions.

TYPE: Size

_instance

Optional uninitialized expansion instance, following Torch.

TYPE: MultivariateStudentT or None DEFAULT: None

RETURNS DESCRIPTION
MultivariateStudentT

Expanded distribution without another matrix factorization.

Source code in src/quivers/continuous/_multivariate_student_t.py
def expand(
    self, batch_shape: Sequence[int], _instance=None
) -> MultivariateStudentT:
    """Expand only batch axes while retaining the shared factor.

    Parameters
    ----------
    batch_shape : torch.Size
        Broadcast-compatible new batch dimensions.
    _instance : MultivariateStudentT or None
        Optional uninitialized expansion instance, following Torch.

    Returns
    -------
    MultivariateStudentT
        Expanded distribution without another matrix factorization.
    """
    new = self._get_checked_instance(MultivariateStudentT, _instance)
    batch_shape = torch.Size(batch_shape)
    new._normal = self._normal.expand(batch_shape)
    new.df = self.df.expand(batch_shape)
    new.loc = new._normal.loc
    new.scale_tril = new._normal.scale_tril
    super(MultivariateStudentT, new).__init__(
        batch_shape, self.event_shape, validate_args=False
    )
    new._validate_args = self._validate_args
    return new

ConditionalMultivariateStudentT

ConditionalMultivariateStudentT(domain: AnySpace, codomain: ContinuousSpace, hidden_dim: int | Sequence[int] | None = None, param_source: ParamSource | None = None, param_source_option: str | None = None)

Bases: ConditionalMultivariateNormal

Learn a Student radial scale alongside the existing Gaussian heads.

PARAMETER DESCRIPTION
domain

Input carrier and real-vector response space.

TYPE: AnySpace

codomain

Input carrier and real-vector response space.

TYPE: AnySpace

hidden_dim

Parameter-network hidden dimensions.

TYPE: int or Sequence[int] or None DEFAULT: None

param_source

Reusable source emitting location, packed Cholesky, and one df head.

TYPE: ParamSource or None DEFAULT: None

param_source_option

Existing parameter-source strategy.

TYPE: str or None DEFAULT: None

Source code in src/quivers/continuous/families.py
def __init__(
    self,
    domain: AnySpace,
    codomain: ContinuousSpace,
    hidden_dim: int | Sequence[int] | None = None,
    param_source: ParamSource | None = None,
    param_source_option: str | None = None,
) -> None:
    super().__init__(domain, codomain)
    d = codomain.dim - self._event_offset
    if d < 1:
        raise ValueError("Gaussian coordinate dimension must be positive")
    n_tril = d * (d + 1) // 2
    self.param_source = _make_source(
        domain,
        d + n_tril + self._extra_raw_parameters,
        hidden_dim,
        param_source=param_source,
        param_source_option=param_source_option,
    )
    self._d = d
    self._n_tril = n_tril

Matrix-normal factors

MatrixNormal accepts independently exclusive row_covariance / row_scale_tril and col_covariance / col_scale_tril arguments. Factor inputs use triangular solves and draws directly; covariance properties are materialized lazily. mean, entrywise variance, and batch expand retain rectangular event dimensions. See the matrix-prior guide.

MatrixNormal

MatrixNormal(loc: Tensor, row_covariance: Tensor | None = None, col_covariance: Tensor | None = None, validate_args: bool | None = None, *, row_scale_tril: Tensor | None = None, col_scale_tril: Tensor | None = None)

Bases: Distribution

The normal law on n x p matrices with Kronecker covariance.

X ~ MN(M, U, V) when its row-major vectorization is normal with mean that of M and covariance U (x) V: entries X[i, j] and X[k, l] covary as U[i, k] V[j, l]. With U = A A^T and V = B B^T a draw is M + A Z B^T for a standard normal Z, and the log density is -(np/2) log 2 pi - (p/2) log det U - (n/2) log det V - tr(V^-1 R^T U^-1 R) / 2 at a residual R = X - M.

PARAMETER DESCRIPTION
loc

The mean, (..., n, p).

TYPE: Tensor

row_covariance

The row covariance U, (..., n, n); exclusive with its factor.

TYPE: Tensor or None DEFAULT: None

col_covariance

The column covariance V, (..., p, p); exclusive with its factor.

TYPE: Tensor or None DEFAULT: None

row_scale_tril

Lower Cholesky factors of the respective covariances. Supplying factors avoids covariance construction and factorization during scoring.

TYPE: Tensor or None DEFAULT: None

col_scale_tril

Lower Cholesky factors of the respective covariances. Supplying factors avoids covariance construction and factorization during scoring.

TYPE: Tensor or None DEFAULT: None

validate_args

Whether to validate the arguments and values.

TYPE: bool | None DEFAULT: None

Source code in src/quivers/continuous/_matrix.py
def __init__(
    self,
    loc: Tensor,
    row_covariance: Tensor | None = None,
    col_covariance: Tensor | None = None,
    validate_args: bool | None = None,
    *,
    row_scale_tril: Tensor | None = None,
    col_scale_tril: Tensor | None = None,
) -> None:
    if (row_covariance is None) == (row_scale_tril is None):
        raise ValueError(
            "MatrixNormal requires exactly one row covariance or factor"
        )
    if (col_covariance is None) == (col_scale_tril is None):
        raise ValueError(
            "MatrixNormal requires exactly one column covariance or factor"
        )
    if loc.ndim < 2:
        raise ValueError("MatrixNormal loc must have two event axes")
    rows, cols = loc.shape[-2:]
    row = row_covariance if row_covariance is not None else row_scale_tril
    col = col_covariance if col_covariance is not None else col_scale_tril
    assert row is not None and col is not None
    if row.shape[-2:] != (rows, rows) or col.shape[-2:] != (cols, cols):
        raise ValueError(
            "MatrixNormal row/column matrices must match loc event axes"
        )
    batch_shape = torch.broadcast_shapes(
        loc.shape[:-2], row.shape[:-2], col.shape[:-2]
    )
    dtype = torch.promote_types(
        loc.dtype, torch.promote_types(row.dtype, col.dtype)
    )
    self.loc = loc.to(dtype=dtype).expand(*batch_shape, rows, cols)
    # Keep parameter batches unbroadcast: a shared covariance is factored
    # once even when the location supplies many observation batches.
    row = row.to(dtype=dtype)
    col = col.to(dtype=dtype)
    if row_covariance is not None:
        self.row_covariance = row
    else:
        self.row_scale_tril = row
    if col_covariance is not None:
        self.col_covariance = col
    else:
        self.col_scale_tril = col
    super().__init__(
        batch_shape=batch_shape,
        event_shape=torch.Size((rows, cols)),
        validate_args=validate_args,
    )
    # Validation precedes factorization and lazy properties retain the authored
    # parameterization. In particular, factor inputs never form covariance products.
    self._row_tril = self.row_scale_tril
    self._col_tril = self.col_scale_tril

mean property

mean: Tensor

The broadcast mean matrix.

RETURNS DESCRIPTION
Tensor

The corresponding batched matrix values.

variance property

variance: Tensor

Entrywise variances from the two factor row norms.

RETURNS DESCRIPTION
Tensor

The corresponding batched matrix values.

row_covariance

row_covariance() -> Tensor

The row covariance, materialized only when requested.

RETURNS DESCRIPTION
Tensor

The corresponding batched matrix values.

Source code in src/quivers/continuous/_matrix.py
@_tensor_lazy_property
def row_covariance(self) -> Tensor:
    """The row covariance, materialized only when requested.

    Returns
    -------
    torch.Tensor
        The corresponding batched matrix values.
    """
    return self.row_scale_tril @ self.row_scale_tril.transpose(-1, -2)

col_covariance

col_covariance() -> Tensor

The column covariance, materialized only when requested.

RETURNS DESCRIPTION
Tensor

The corresponding batched matrix values.

Source code in src/quivers/continuous/_matrix.py
@_tensor_lazy_property
def col_covariance(self) -> Tensor:
    """The column covariance, materialized only when requested.

    Returns
    -------
    torch.Tensor
        The corresponding batched matrix values.
    """
    return self.col_scale_tril @ self.col_scale_tril.transpose(-1, -2)

row_scale_tril

row_scale_tril() -> Tensor

The row Cholesky factor, computed once for covariance inputs.

RETURNS DESCRIPTION
Tensor

The corresponding batched matrix values.

Source code in src/quivers/continuous/_matrix.py
@_tensor_lazy_property
def row_scale_tril(self) -> Tensor:
    """The row Cholesky factor, computed once for covariance inputs.

    Returns
    -------
    torch.Tensor
        The corresponding batched matrix values.
    """
    return torch.linalg.cholesky(self.row_covariance)

col_scale_tril

col_scale_tril() -> Tensor

The column Cholesky factor, computed once for covariance inputs.

RETURNS DESCRIPTION
Tensor

The corresponding batched matrix values.

Source code in src/quivers/continuous/_matrix.py
@_tensor_lazy_property
def col_scale_tril(self) -> Tensor:
    """The column Cholesky factor, computed once for covariance inputs.

    Returns
    -------
    torch.Tensor
        The corresponding batched matrix values.
    """
    return torch.linalg.cholesky(self.col_covariance)

expand

expand(batch_shape, _instance=None)

Expand batch axes without factoring or materializing covariances.

PARAMETER DESCRIPTION
batch_shape

Requested batch dimensions.

TYPE: Size

_instance

Optional distribution instance used by Torch expansion.

TYPE: MatrixNormal or None DEFAULT: None

RETURNS DESCRIPTION
MatrixNormal

A distribution sharing the existing parameter tensors.

Source code in src/quivers/continuous/_matrix.py
def expand(self, batch_shape, _instance=None):
    """Expand batch axes without factoring or materializing covariances.

    Parameters
    ----------
    batch_shape : torch.Size
        Requested batch dimensions.
    _instance : MatrixNormal or None
        Optional distribution instance used by Torch expansion.

    Returns
    -------
    MatrixNormal
        A distribution sharing the existing parameter tensors.
    """
    new = self._get_checked_instance(MatrixNormal, _instance)
    batch_shape = torch.Size(batch_shape)
    rows, cols = self.event_shape
    new.loc = self.loc.expand(*batch_shape, rows, cols)
    new.row_scale_tril = self._row_tril.expand(*batch_shape, rows, rows)
    new.col_scale_tril = self._col_tril.expand(*batch_shape, cols, cols)
    new._row_tril, new._col_tril = new.row_scale_tril, new.col_scale_tril
    super(MatrixNormal, new).__init__(
        batch_shape, self.event_shape, validate_args=False
    )
    new._validate_args = self._validate_args
    return new

rsample

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

Draw M + A Z B^T.

PARAMETER DESCRIPTION
sample_shape

Leading sample axes.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

The draws, (*sample_shape, *batch_shape, n, p).

Source code in src/quivers/continuous/_matrix.py
def rsample(self, sample_shape: torch.Size = torch.Size()) -> Tensor:
    """Draw ``M + A Z B^T``.

    Parameters
    ----------
    sample_shape : torch.Size
        Leading sample axes.

    Returns
    -------
    torch.Tensor
        The draws, ``(*sample_shape, *batch_shape, n, p)``.
    """
    shape = self._extended_shape(torch.Size(sample_shape))
    noise = torch.randn(shape, dtype=self.loc.dtype, device=self.loc.device)
    return self.loc + self._row_tril @ noise @ self._col_tril.transpose(-1, -2)

log_prob

log_prob(value: Tensor) -> Tensor

The log density at a matrix.

PARAMETER DESCRIPTION
value

The matrices, (..., n, p).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The log densities.

Source code in src/quivers/continuous/_matrix.py
def log_prob(self, value: Tensor) -> Tensor:
    """The log density at a matrix.

    Parameters
    ----------
    value : torch.Tensor
        The matrices, ``(..., n, p)``.

    Returns
    -------
    torch.Tensor
        The log densities.
    """
    if self._validate_args:
        self._validate_sample(value)
    rows, cols = self.event_shape
    residual = value - self.loc
    whitened = torch.linalg.solve_triangular(
        self._row_tril.expand(*residual.shape[:-2], rows, rows),
        residual,
        upper=False,
    )
    whitened = torch.linalg.solve_triangular(
        self._col_tril.expand(*residual.shape[:-2], cols, cols),
        whitened.transpose(-1, -2),
        upper=False,
    )
    quadratic = whitened.pow(2).sum((-1, -2))
    row_log_det = 2.0 * self._row_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1)
    col_log_det = 2.0 * self._col_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1)
    return -0.5 * (
        rows * cols * math.log(2.0 * math.pi)
        + cols * row_log_det
        + rows * col_log_det
        + quadratic
    )