Membership Circuits (MCs)

A Membership Circuit turns a smooth and decomposable probabilistic circuit into a hypothesis test. For every data row it tests the membership hypothesis “this row is a sample of the circuit” and returns a p-value. A small p-value is evidence against the hypothesis, for example because the row is an anomaly or comes from another distribution.

Reference

Membership Circuits are described in:

The combination rules are described in:

Overview

The p-value of a row is computed in one bottom-up pass over the circuit:

  • A leaf turns its observed value into a univariate p-value from its cumulative distribution function (left, right or two-sided).

  • A product node merges the p-values of its children with a product rule. The children of a product node are independent under the circuit, so rules for independent p-values (Fisher, Simes) are valid here, as are rules that are valid under arbitrary dependence.

  • A sum node merges the p-values of its children with a sum rule. A row comes from one child only, and only the p-value of that child is known to be valid. The sum rules are valid in this situation.

  • Every inner node clips its result to \([0, 1]\). The p-value of the root is the result.

The result is a valid p-value: under the membership hypothesis the probability that it falls below a level \(\varepsilon\) is at most \(\varepsilon\). Most rules are conservative, some more than others; the choice of the rules decides the power of the test.

Combination Rules

A spflow.zoo.mc.MembershipTestConfig holds one sum rule and one product rule. Both are required; there are no defaults.

Rule

Node type

Formula and validity

spflow.zoo.mc.ArithmeticMeanK

sum

\(K \sum_i w_i p_i\); valid at sum nodes.

spflow.zoo.mc.ArithmeticMeanSqrtW

sum

\(S \sum_i \sqrt{w_i}\, p_i\) with \(S = \sum_j \sqrt{w_j}\); valid at sum nodes, with the smallest valid constant \(S^2 \le K\).

spflow.zoo.mc.WeightedArithmeticMean

sum

\(c \sum_i a_i p_i\) with coefficients from a callable; valid if \(c \ge \sum_i w_i / a_i\), which is checked.

spflow.zoo.mc.MaxP

sum, product

\(\max_i p_i\); valid at every node, very conservative.

spflow.zoo.mc.Fisher

product

\(-2 \sum_i \log p_i\) against \(\chi^2_{2k}\); valid for independent children, exact if their p-values are uniform.

spflow.zoo.mc.Simes

product

\(\min_i (k / i)\, p_{(i)}\); valid for independent children.

spflow.zoo.mc.Bonferroni

product

\(k\, p_{(1)}\); valid under any dependence.

spflow.zoo.mc.HarmonicMean

product

\(a_k\) times the harmonic mean; valid under any dependence.

spflow.zoo.mc.HarmonicMeanStar

product

Harmonic* rule, never larger than the harmonic mean rule; valid under any dependence. Under evaluation.

spflow.zoo.mc.GridHarmonic

product

Grid harmonic rule; valid under any dependence. Under evaluation, and more expensive than the other rules.

Missing Values

NaN marks a missing value. A row with missing values is tested on its observed variables only: a node whose variables are all missing is left out, a product node merges its observed children, and a row without any observed value gets the p-value 1. The result equals the p-value under the circuit in which the missing variables are marginalized out. It is a valid test of the observed part of the row only if the missingness does not depend on the values of the row.

Discrete Leaves

The p-value of a discrete leaf has three modes (discrete_mode):

  • "exact": the tail probability includes the probability of the observed value. Valid and conservative.

  • "midp": half of the probability of the observed value is counted. The mid-p value is not a valid p-value in general.

  • "randomized": a uniform random fraction of the probability of the observed value is counted. The p-value of the leaf is then exactly uniform, at the price of a decision that depends on a random number. Pass seed for reproducible results.

Goodness of Fit

The p-values of held-out rows also tell whether the circuit fits the data: if the rows are samples of the circuit, small p-values are not more frequent than under the uniform distribution. spflow.zoo.mc.binomial_gof() and spflow.zoo.mc.ks_gof() test this, and spflow.zoo.mc.gof_report() collects both. A small result means misfit. A large result is no proof of fit, because a conservative combination rule can hide a misfit. Rows that were used to fit the circuit give optimistic p-values and should not be used.

Supported Modules

The pass supports Sum, Product, Cat, ElementwiseSum, ElementwiseProduct, OuterProduct, Factorize, RepetitionMixingLayer, the split modules as the input of ElementwiseProduct or OuterProduct, and spflow.zoo.rat.RatSPN. The supported leaf families are Normal, LogNormal, Exponential, Gamma, Laplace, Uniform, Histogram, Bernoulli, Categorical, Poisson, Geometric, Binomial and Hypergeometric. Every other module or leaf raises an UnsupportedOperationError.

Minimal Example

import torch
from spflow.meta import Scope
from spflow.modules.leaves import Normal
from spflow.modules.products import Product
from spflow.modules.sums import Sum
from spflow.zoo.mc import (
    ArithmeticMeanSqrtW,
    HarmonicMean,
    MembershipCircuit,
    MembershipTestConfig,
    gof_report,
)

# A mixture of two product nodes over two variables.
def normal(variable, loc, scale):
    return Normal(scope=Scope([variable]), loc=torch.tensor([[[loc]]]), scale=torch.tensor([[[scale]]]))

circuit = Sum(
    inputs=[
        Product(inputs=[normal(0, 0.0, 1.0), normal(1, 1.0, 2.0)]),
        Product(inputs=[normal(0, 4.0, 1.0), normal(1, -2.0, 1.0)]),
    ],
    weights=[0.3, 0.7],
)

config = MembershipTestConfig(sum_rule=ArithmeticMeanSqrtW(), product_rule=HarmonicMean())
mc = MembershipCircuit(circuit, config)

x = torch.tensor(
    [
        [0.1, 1.5],           # typical for the first component
        [9.0, 9.0],           # far away from both components
        [4.2, float("nan")],  # second variable missing
    ]
)
p = mc(x)  # one p-value per row, shape (3,)

# Goodness of fit on rows that were not used for training (here: samples of the circuit).
held_out = circuit.sample(num_samples=2000)
report = gof_report(mc(held_out))

Calling mc(x) returns p-values, not log-likelihoods; the log-likelihood of the wrapped circuit is available as mc.log_likelihood(x). The function spflow.zoo.mc.membership_pvalues() computes the same p-values without a wrapper.

API Reference

Membership Circuit

class spflow.zoo.mc.MembershipCircuit(module, config, *, validate=True)[source]

Bases: Wrapper

Wrap a probabilistic circuit as a test of the membership hypothesis.

The null hypothesis of a row is that it is a sample of the distribution of the wrapped circuit. Calling the wrapper on data returns one p-value per row; a small p-value is evidence against the hypothesis, for example because the row is an anomaly. The p-values are computed by spflow.zoo.mc.membership_pvalues(), where the supported modules, the treatment of missing values and the accuracy are described.

forward returns p-values and not log-likelihoods, unlike every other SPFlow module: mc(data) is mc.pvalues(data). The log-likelihood of the wrapped circuit stays available as mc.log_likelihood(data). Sampling, expectation-maximization and structural marginalization are delegated to the wrapped circuit, so the wrapper can be trained like the circuit itself.

module

The wrapped circuit.

config

Test configuration: sum rule, product rule, test side and discrete mode.

__init__(module, config, *, validate=True)[source]

Initialize the wrapper.

Parameters:
  • module (Module) – Circuit with a single root node. It is not copied: later changes of its parameters change the p-values.

  • config (MembershipTestConfig) – Test configuration.

  • validate (bool) – If True, the p-value pass runs on a small probe (one complete row, and one row per variable in which only that variable is observed), so that an unsupported module or leaf, a root that is not a single node, a sum node whose children have different scopes and invalid sum-rule coefficients raise here and not at the first use. The time is that of a pass over as many rows as the circuit has variables, plus one. The rows are evaluated in several passes, so that the memory does not grow with the square of the number of variables.

Raises:
  • InvalidTypeError – If module is not a module or config is not a MembershipTestConfig.

  • ShapeError – With validate, if the circuit does not have a single root node.

  • StructureError – With validate, if the children of a sum node have different scopes.

  • UnsupportedOperationError – With validate, if the circuit contains a module or a leaf that is not supported.

  • InvalidWeightsError – With validate, if the weights of a sum module are not finite.

  • InvalidParameterError – With validate, if the coefficients of the sum rule are not valid. Degenerate leaf parameters are found only if they show at the probe value 0.

forward(data, *, seed=None)[source]

Return the membership p-values of the rows of data, see pvalues().

This differs from the other SPFlow modules, whose forward pass is the log-likelihood.

Return type:

Tensor

log_likelihood(data, cache=None)[source]

Compute the log-likelihood of the wrapped circuit.

Parameters:
  • data (Tensor) – Input data of shape (N, D); NaN values are marginalized.

  • cache (Cache | None) – Optional cache for intermediate results.

Return type:

Tensor

Returns:

Log-likelihood tensor of the wrapped circuit.

marginalize(marg_rvs, prune=True, cache=None)[source]

Marginalize variables out of the wrapped circuit and wrap the result with the same test.

The structural marginalization is that of the wrapped circuit and has its limits: several layer modules do not implement it. Missing values in the data (NaN) need no structural marginalization and work for every supported circuit.

Parameters:
  • marg_rvs (list[int]) – Indices of the variables to marginalize out.

  • prune (bool) – Whether to prune modules that become unnecessary.

  • cache (Cache | None) – Optional cache for intermediate results.

Return type:

MembershipCircuit | None

Returns:

Membership circuit over the remaining variables, or None if no variable remains. It is validated when it is built if and only if this wrapper was.

pvalues(data, *, seed=None)[source]

Compute the membership p-value of every row of data.

Parameters:
  • data (Tensor) – Rows to test, of shape (N, D); column j holds variable j. NaN marks a missing value: the row is then tested on its observed variables only. The missingness must be independent of the values.

  • seed (int | None) – Seed of the random numbers of discrete_mode="randomized"; None uses the global random number generator of torch. Two calls with the same seed use the same numbers: evaluate a data set in one call, or use another seed for every batch. Ignored in the other modes, apart from the check of its type and range.

Return type:

Tensor

Returns:

P-values of shape (N,) in float64, without gradients. See spflow.zoo.mc.membership_pvalues() for the details and the exceptions.

sample(num_samples=None, data=None, is_mpe=False, cache=None, return_leaf_params=False)[source]

Sample from the wrapped circuit.

The call goes to the public sample of the wrapped circuit and not to its _sample hook, because a circuit such as RatSPN prepares the sampling context in sample.

Parameters:
  • num_samples (int | None) – Number of samples to generate.

  • data (Tensor | None) – Tensor with NaN at the entries to sample; other entries are evidence.

  • is_mpe (bool) – If True, return the most probable values instead of random samples.

  • cache (Cache | None) – Optional cache for intermediate results.

  • return_leaf_params (bool) – If True, also return the leaf parameters of the samples.

Return type:

Tensor | tuple[Tensor, list[LeafParamRecord]]

Returns:

Samples of shape (N, D), with the leaf-parameter records if requested.

spflow.zoo.mc.membership_pvalues(model, data, config, *, seed=None)[source]

Compute the membership p-value of every row of data under a circuit.

The null hypothesis of a row is that it is a sample of the distribution of model. A small p-value is evidence against it. The p-value is valid (its probability to fall below a level is at most that level under the null hypothesis) if the rules of config are valid for their node type; all rules of this package are, except that discrete_mode="midp" gives no guarantee.

The pass runs in float64 and without gradients, whatever the dtype of the model. The model is not moved, cast or modified. The parameters are read as they are: the accuracy of the p-values of a float32 model is limited by its rounded parameters, see spflow.zoo.mc.leaf_pvalues().

Supported modules: Sum, RepetitionMixingLayer, ElementwiseSum, Product, ElementwiseProduct, OuterProduct, Factorize, Cat, the three split modules as the direct input of ElementwiseProduct or OuterProduct, RatSPN and the leaf families of spflow.zoo.mc.leaf_pvalues(). The circuit must be smooth and decomposable. A RepetitionMixingLayer over an input with a single repetition counts one child per weight; its p-value is valid, but up to K times larger than that of the input.

Parameters:
  • model (Module) – Circuit with a single root node, that is with output shape (1, 1, 1).

  • data (Tensor) – Rows to test, of shape (N, D) with one column per variable; column j holds variable j of the scope of the model. NaN marks a missing value: the row is then tested on its observed variables only (marginal semantics). The missingness must be independent of the values. A row without any observed value gets the p-value 1.

  • config (MembershipTestConfig) – Test configuration: sum rule, product rule, test side and discrete mode.

  • seed (int | None) – Seed of the random numbers of discrete_mode="randomized". One number is drawn per row and column of data (also for columns outside the scope of the model), on the CPU, so that the result does not depend on the device or on the structure of the circuit. It does depend on the position of a row in data and on the number of columns. Two calls with the same seed use the same numbers: evaluate a data set in one call, or use another seed for every batch. None uses the global random number generator of torch. Ignored in the other modes, apart from the check of its type and range.

Return type:

Tensor

Returns:

P-values of shape (N,) in float64, in [0, 1], on the device of the model and without gradients.

Raises:
  • InvalidTypeError – If model is not a module, config is not a MembershipTestConfig, data is not a real-valued tensor (for example interval evidence), seed is not an integer, or a combination rule returns something else than a float64 tensor.

  • ShapeError – If data is not two-dimensional or has fewer columns than the scope of the model needs, if the model does not have a single root node, if the shapes of the inputs of a module do not fit together, or if a combination rule does not return one p-value per node.

  • StructureError – If the children of a sum node do not have the same scope, so that a row with missing values is missing for some children only (the sum is not smooth).

  • UnsupportedOperationError – If the circuit contains a module or a leaf that is not supported.

  • InvalidWeightsError – If the weights of a sum module are not finite.

  • InvalidParameterError – If seed lies outside [-2**63, 2**64 - 1], if a leaf has degenerate parameters, if the coefficients of the sum rule fail their validity check or if a p-value is NaN.

class spflow.zoo.mc.MembershipTestConfig(sum_rule, product_rule, side='both', discrete_mode='exact')[source]

Bases: object

Configuration of a membership test.

sum_rule

Combination rule used at every sum node.

product_rule

Combination rule used at every product node.

side

Test side of every leaf. "left" rejects small values, "right" rejects large values and "both" rejects values in either tail.

discrete_mode

P-value definition at discrete leaves. "exact" is valid and conservative. "midp" counts half of the observed atom and is not a valid p-value in general. "randomized" is exactly uniform under the leaf distribution, at the price of a random decision.

Raises:
  • InvalidTypeError – If sum_rule is not a SumCombination or product_rule is not a ProductCombination, or if the name of a rule is not a non-empty string.

  • InvalidParameterError – If side or discrete_mode has an unknown value.

name()[source]

Return a stable identifier of the configuration.

Return type:

str

Returns:

"{side}_S_{sum rule}_P_{product rule}", followed by "_D_{discrete_mode}" if the discrete mode is not "exact".

discrete_mode: Literal['exact', 'midp', 'randomized'] = 'exact'
product_rule: ProductCombination
side: Literal['both', 'left', 'right'] = 'both'
sum_rule: SumCombination

Sum Rules

class spflow.zoo.mc.ArithmeticMeanK[source]

Bases: WeightedArithmeticMean

AM-k rule: the weighted mean of the child p-values times the number of children.

Formula: p = K * sum_i w_i * p_i, the WeightedArithmeticMean with am_k_coefficients(). K counts every child of the sum node, also a child with weight zero.

Validity: valid at sum nodes under the mixture null, for any dependence between the children.

__init__()[source]

Initialize the rule with the name "AMean_K".

class spflow.zoo.mc.ArithmeticMeanSqrtW[source]

Bases: WeightedArithmeticMean

AM-sqrtW rule: arithmetic mean with square-root coefficients and the smallest valid constant.

Formula: p = S * sum_i sqrt(w_i) * p_i with S = sum_j sqrt(w_j), the WeightedArithmeticMean with am_sqrtw_coefficients(). The constant S^2 is at most K; the rule equals AM-k for uniform weights and tends to the p-value of the dominant child if one weight tends to 1.

Validity: valid at sum nodes under the mixture null, for any dependence between the children.

__init__()[source]

Initialize the rule with the name "AMean_sqrtW".

class spflow.zoo.mc.WeightedArithmeticMean(coefficients, name, check_validity=True)[source]

Bases: SumCombination

Weighted arithmetic mean of the child p-values with coefficients from a callable.

Formula: p = c * sum_i a_i * p_i with (a, c) = coefficients(weights, context). The coefficient function is called once per call of combine(), that is once per sum module and not once per row.

Validity: under the model null a row comes from child i with probability w_i, and only the p-value of that child is known to be valid. The rule is a valid test in this situation, without any assumption on the dependence between the children, if c >= sum_i w_i / a_i with a_i > 0 wherever w_i > 0: given component i the result is at least c * a_i * p_i, so it falls below eps with probability at most eps / (c * a_i), and the mixture over i gives at most eps * sum_i w_i / (c * a_i) <= eps. With check_validity=True this inequality is tested (with a relative tolerance of 1e-9) on every call.

coefficients

Function (weights, context) -> (a, c). weights are the normalized mixture weights of shape (..., K) in float64, a are non-negative coefficients of the same shape and c is a positive constant per sum node of shape (...).

name

Stable short identifier of the rule.

check_validity

Whether combine() tests the validity condition.

__init__(coefficients, name, check_validity=True)[source]

Initialize the rule.

Parameters:
  • coefficients (Callable[[Tensor, SumNodeContext], tuple[Tensor, Tensor]]) – Function (weights, context) -> (a, c), see the class documentation.

  • name (str) – Stable short identifier of the rule, used in configuration names.

  • check_validity (bool) – If True, combine() raises when the coefficients violate the validity condition c >= sum_i w_i / a_i. Switch it off only for a null hypothesis that differs from the mixture null on purpose. The check never changes the result.

Raises:
  • InvalidTypeError – If coefficients is not callable or name is not a string.

  • InvalidParameterError – If name is empty.

combine(p, *, weights=None, observed=None, context=None)[source]

Return c * sum_i a_i * p_i for each sum node.

Parameters:
  • p (Tensor) – Child p-values with the children on the last axis, shape (..., K).

  • weights (Tensor | None) – Normalized mixture weights of shape (..., K). Required.

  • observed (Tensor | None) – Boolean mask, broadcastable to p. A sum node has either all children observed or none, so the mask only selects the rows without any observed child, which give exactly 1. Rows with some observed children are merged over all K children. None means that all entries are observed.

  • context (SumNodeContext | None) – Information about the sum nodes for the coefficient function. Defaults to SumNodeContext(num_children=K).

Return type:

Tensor

Returns:

Merged p-values in float64, not clipped, with the leading axes of p broadcast against weights.shape[:-1].

Raises:
  • InvalidParameterError – If weights is missing, or if check_validity is set and the coefficients violate the validity condition.

  • InvalidTypeError – If observed is not a boolean tensor or the coefficient function does not return a tuple of two tensors.

  • ShapeError – If weights or observed does not fit to p, or the coefficients do not have the shapes weights.shape and weights.shape[:-1].

spflow.zoo.mc.am_k_coefficients(weights, context)[source]

Return the coefficients of the AM-k rule: a_i = w_i and c = K.

sum_i w_i / a_i is the number of children with a positive weight, so the validity condition holds with equality if all weights are positive. A child with weight zero is counted in K.

Parameters:
  • weights (Tensor) – Normalized mixture weights with the children on the last axis, shape (..., K).

  • context (SumNodeContext) – Information about the sum nodes; context.num_children is K.

Return type:

tuple[Tensor, Tensor]

Returns:

Tuple (a, c) with a of shape (..., K) and c of shape (...).

spflow.zoo.mc.am_sqrtw_coefficients(weights, context)[source]

Return the coefficients of the AM-sqrtW rule: a_i = sqrt(w_i) / S and c = S^2.

S = sum_j sqrt(w_j). Among all coefficients that sum to 1 these give the smallest constant that satisfies the validity condition, c = sum_i w_i / a_i = S^2 <= K. The coefficients and the constant belong together: a = w with c = S^2 is not valid.

Parameters:
  • weights (Tensor) – Normalized mixture weights with the children on the last axis, shape (..., K).

  • context (SumNodeContext) – Information about the sum nodes. Not used.

Return type:

tuple[Tensor, Tensor]

Returns:

Tuple (a, c) with a of shape (..., K) and c of shape (...).

class spflow.zoo.mc.SumNodeContext(num_children, module=None, scope=None)[source]

Bases: object

Read-only information about the sum nodes that a coefficient function serves.

num_children

Number of children K of each sum node (the fan-in).

module

Sum module that holds the nodes, if the rule is called from a circuit pass.

scope

Joint scope of the module, if the rule is called from a circuit pass.

module: Module | None = None
num_children: int
scope: Scope | None = None
class spflow.zoo.mc.MaxP[source]

Bases: SumCombination, ProductCombination

Maximum of the child p-values, the only rule that is valid at every node type.

Formula: p = max_i p_i over the observed children.

Validity: at a sum node the maximum is at least the p-value of the mixture component that generated the row, and that p-value is valid. At a product node the maximum is at least the p-value of every single child, so the rule is valid under any dependence between the children (the intersection-union test). It rejects only if every child rejects, which makes it very conservative.

combine(p, *, weights=None, observed=None, context=None)[source]

Return the maximum of the observed child p-values of each node.

Parameters:
  • p (Tensor) – Child p-values with the children on the last axis, shape (..., K).

  • weights (Tensor | None) – Mixture weights of shape (..., K) if the rule is used at sum nodes. Only their shape is used: the result is broadcast to their leading axes. At a sum node every child enters the maximum, whatever its weight, also a child with weight zero.

  • observed (Tensor | None) – Boolean mask, broadcastable to p. None means that all entries are observed.

  • context (SumNodeContext | None) – Ignored.

Return type:

Tensor

Returns:

Maximum over the observed children in float64, with shape p.shape[:-1], or that shape broadcast against weights.shape[:-1] if weights is given (as a view that must not be written to). A row without an observed child gives exactly 1; a row with a NaN at an observed child gives NaN.

Raises:
  • InvalidTypeError – If observed is not a boolean tensor.

  • ShapeError – If p has no children axis, or observed or weights does not fit to p.

name: str = 'maxP'

Product Rules

All product rules are spflow.zoo.mc.ProductCombination rules and follow its conventions.

class spflow.zoo.mc.Fisher[source]

Fisher’s method: the sum of the log p-values against a chi-squared distribution.

Formula: T = -2 * sum_i log(max(p_i, 1e-300)) and p = Q(k, T / 2), where k is the number of observed children and Q is the regularized upper incomplete gamma function, that is the survival function of the chi-squared distribution with 2 * k degrees of freedom.

Validity: valid if the children are independent, which holds at a product node under the model null, and exact if their p-values are uniform in addition. It is not valid under arbitrary dependence between the children.

Accuracy: the upper tail is computed directly with torch.special.gammaincc. That function has a relative error of about 2e-9 for more than 20 children when T / 2 is within 30 percent of k; elsewhere the relative error is at most about 5e-13 for up to 250 children and about 2e-15 times k for more (2e-12 for 1000 children). The rule is therefore non-decreasing in its inputs only up to floating-point rounding. The inputs must not exceed 1: if their product exceeds 1, the result is NaN.

name: str = 'Fish'
class spflow.zoo.mc.Simes[source]

Simes’ method.

Formula: p = min_i (k / i) * p_(i) over i = 1, ..., k, where k is the number of observed children and p_(1) <= ... <= p_(k) are their sorted p-values. The term i = 1 is Bonferroni’s method, so the result is never larger than that of Bonferroni.

Validity: valid if the children are independent, which holds at a product node under the model null (exact for uniform p-values), and also under positive regression dependence. It is not valid under arbitrary dependence between the children.

name: str = 'Simes'
class spflow.zoo.mc.Bonferroni[source]

Bonferroni’s method: the smallest p-value times the number of children.

Formula: p = k * p_(1), where k is the number of observed children and p_(1) is the smallest of their p-values.

Validity: valid under any dependence between the children. Under independence it is slightly conservative.

name: str = 'Bonf'
class spflow.zoo.mc.HarmonicMean[source]

Harmonic mean of the child p-values with the multiplier of Vovk and Wang (2020).

Formula: p = a_k * k / sum_i (1 / max(p_i, 1e-300)), where k is the number of observed children, a_1 = 1, a_2 = 2 and a_k = (y_k + k)^2 / ((y_k + 1) * k) for k >= 3 with y_k the positive root of y^2 = k * ((y + 1) * log(y + 1) - y) (spflow.zoo.mc.constants.harmonic_mean_multiplier()). a_k is the full multiplier.

Validity: valid under any dependence between the children; conservative under independence. The value a_2 = 2 is required for that: the smaller constant e * log(2) is slightly anti-conservative under adversarial dependence.

Reference: V. Vovk and R. Wang (2020), “Combining p-values via averaging”, Biometrika 107(4) (arXiv:1212.4966), for a_k with k >= 3; V. Vovk, B. Wang and R. Wang (2022), “Admissible ways of merging p-values under arbitrary dependence”, Annals of Statistics (arXiv:2007.14208), Proposition 8.1, for a_2 = 2.

name: str = 'HMean_ada2'
class spflow.zoo.mc.HarmonicMeanStar[source]

Harmonic* rule of Vovk, Wang and Wang (2022), an admissible improvement of the harmonic mean.

Formula for k >= 3 observed children with sorted p-values p_(1) <= ... <= p_(k):

p = min(1, min over m = 1..k of (1/c + (m - 1)/d) / sum_{j <= m} 1 / p_(j))

with 1/c = y_k + k and 1/d = (y_k + k) / (y_k + 1), y_k as in HarmonicMean. For k = 2 the rule is min(2 * p_(1), 1). The result is exactly 0 if an observed input is exactly 0. The term m = k is the value of HarmonicMean, so the result is never larger than that. Before the clip at 1 it is equal to that value for equal inputs and never smaller than d times that value.

Validity: valid under any dependence between the children; conservative under independence.

Status: this rule is an option under evaluation.

Inputs below 1e-300 do not occur in a circuit pass: leaf p-values are at least 1e-300, and this rule and every valid sum rule return at least their smallest input (up to rounding). In a direct call with such inputs two properties are lost. First, HarmonicMean raises its inputs to 1e-300 and this rule does not, so the two rules are no longer equal for equal inputs and the bound d does not hold. Second, a term whose sum of reciprocals overflows (for m equal inputs: below about m * 5.6e-309) is left out of the minimum, so that the term m = 1 decides. The result is then still a valid p-value, but it is only an upper bound of the formula and it is not monotone: raising an input can bring a term back into the minimum and lower the result.

Reference: V. Vovk, B. Wang and R. Wang (2022), “Admissible ways of merging p-values under arbitrary dependence”, Annals of Statistics (arXiv:2007.14208), Theorem 8.2 and Proposition 8.4 with r = -1.

name: str = 'HMean_star'
class spflow.zoo.mc.GridHarmonic[source]

Grid harmonic rule H* of Vovk, Wang and Wang (2022).

Formula for k observed children with l_k = 1 + 1/2 + ... + 1/k:

inside(eps)  <=>  sum_i [l_k * p_i <= eps] / ceil(k * l_k * p_i / eps) >= 1
p = min(1, inf{eps > 0 : inside(eps)})

The result is exactly 0 if an observed input is exactly 0. Before the clip it lies between l_k times the harmonic mean of the inputs and Hommel’s bound l_k * min_i (k / i) * p_(i); for k <= 3 it equals Hommel’s bound, which is then returned directly. It is not ordered against HarmonicMean or HarmonicMeanStar.

Validity: valid under any dependence between the children; conservative under independence.

Status: this rule is an option under evaluation.

Numerics: for k >= 4 the infimum is located by 56 bisection steps on the logarithm of eps between the two bounds, and the upper end is returned. The test of the sum allows for rounding (>= 1 - 4 * k * 2.2e-16), because a floating-point sum of unit fractions can fall just below 1 when the exact sum is 1. The allowance also accepts an eps whose exact sum is below 1 by less than that amount; this is possible only for more than 30 children and was not seen on random inputs. The result is then below the formula by a relative amount of up to 1 / n, with n the largest denominator in the sum, and the level of the test grows by a relative amount of at most about 5 * k * 2.2e-16. The relative resolution is near machine precision for moderate results and about 1.5e-13 near 1e-300, where the logarithm loses digits. The rule is a step function of its inputs: it has no useful gradient, and it is non-decreasing in its inputs only up to floating-point rounding. If the sum of the reciprocals of the inputs overflows (for equal inputs: below about k * 5.6e-309, which does not occur in a circuit pass with leaf p-values of at least 1e-300), Hommel’s bound is returned. It is a valid p-value, but only an upper bound of the formula, and the rule is not monotone across this limit.

Cost: about 56 passes over the children per node, against one sort for the other harmonic rules. A full pass over a RAT-SPN with 64 to 784 variables took 5 to 10 times as long as with HarmonicMean (measured on a CPU).

Reference: V. Vovk, B. Wang and R. Wang (2022), “Admissible ways of merging p-values under arbitrary dependence”, Annals of Statistics (arXiv:2007.14208), Section 7 with Theorem 7.1.

name: str = 'HMean_grid'

Rule Interfaces

class spflow.zoo.mc.PValueCombination[source]

Bases: ABC

Abstract base class of all p-value combination rules.

Subclasses are stateless and must be non-decreasing in every input (up to floating-point rounding).

name

Stable short identifier of the rule, used in configuration names.

abstractmethod combine(p, *, weights=None, observed=None, context=None)[source]

Merge the p-values of the children of each node.

Parameters:
  • p (Tensor) – Child p-values with the children on the last axis, shape (..., K). The tensor is not modified.

  • weights (Tensor | None) – Normalized mixture weights with the children on the last axis, shape (..., K), broadcastable against p in the leading axes. Used by sum rules only.

  • observed (Tensor | None) – Boolean mask, broadcastable to p. False marks an entry that is not a child with a p-value for this row. Values of p at such entries are arbitrary. Product rules and MaxP ignore them. The children of a sum node are observed together or not at all, so the arithmetic-mean rules use the mask only to return 1 for a row without an observed child and merge all K entries of every other row. None means that all entries are observed.

  • context (SumNodeContext | None) – Information about the sum nodes for coefficient functions. Used by sum rules only.

Return type:

Tensor

Returns:

Merged p-values with the children axis removed, in float64. The result is not clipped to [0, 1] unless the formula of the rule contains the clip; the node clips.

name: str
class spflow.zoo.mc.SumCombination[source]

Bases: PValueCombination, ABC

Abstract base class of the rules that are valid at sum nodes.

class spflow.zoo.mc.ProductCombination[source]

Bases: PValueCombination, ABC

Abstract base class of the rules that are valid at product nodes.

Per row a product rule merges the observed children only, with their number k_obs in place of K in every constant of its formula. The product rules of this package share three conventions: a row with one observed child gives the p-value of that child unchanged, a row without an observed child gives exactly 1, and a row with a NaN at an observed child gives NaN. Their inputs must lie in [0, 1].

Leaf P-Values

spflow.zoo.mc.leaf_pvalues(leaf, x, *, side='both', discrete_mode='exact', uniforms=None)[source]

Compute the p-values of observed values under the distributions of a leaf module.

With L = P(X < x), A = P(X = x) and R = P(X > x) under one leaf distribution, the left p-value is L + wl * A and the right p-value is R + wr * A. Continuous families have no atom (A = 0) and ignore discrete_mode. For discrete families the mode sets the weights:

  • "exact": wl = wr = 1. The p-value is valid and conservative by up to one atom. The right p-value is P(X >= x): it includes the observed atom.

  • "midp": wl = wr = 0.5. The mid-p value is not a valid p-value in general: for a Bernoulli leaf with success probability 0.5 and side="both" it equals 0.5 for both outcomes.

  • "randomized": wl = 1 - u and wr = u with the given u in [0, 1). For u uniform and independent of the row, the p-value is exactly uniform under the leaf distribution. The price is a decision that depends on the random number. The left and the right p-value of one observation use the same u and sum to 1.

side="left" returns the left p-value, side="right" the right one and side="both" returns 2 * min(left, right). The result is clamped to [1e-300, 1]; the upper limit is necessary because a two-sided exact p-value of a discrete leaf can exceed 1.

The values of a Categorical leaf have no order. Its p-value is the minimum-likelihood p-value, the same for every side: lt + w * eq with w = 1 (exact), 0.5 (mid-p) or u (randomized), where lt is the probability of all categories that are less likely than the observed one and eq the probability of all categories that are exactly as likely (the observed one included). The comparison uses the model’s own float64 probabilities. A value that is not one of the categories 0, ..., K - 1 gets the smallest p-value 1e-300.

No real value of x raises. For the ordered discrete families (Bernoulli, Poisson, Geometric, Binomial, Hypergeometric), a value that is not an integer or lies outside the support has no atom and uses L = P(X < x) and R = P(X > x) as they are: 2.5 at a Poisson leaf gives the left p-value P(X <= 2) and the right p-value P(X >= 3). Continuous families treat a value outside their support in the same way (L = 0 below the support, R = 0 above it). Infinite values are accepted.

Accuracy: all computations use float64, whatever the dtype of the leaf. A leaf with float32 parameters is evaluated at its rounded parameter values. Compared with the unrounded values, this limits the relative accuracy of its p-values to about 1e-6 near the centre of the distribution and to about 1e-4 in deep tails, where the rounding of the parameters is amplified. The incomplete gamma functions of torch (used by Gamma and Poisson) have a relative error of about 2e-9 where the shape argument is above 20 and the second argument lies within 30 percent of it (within 32 percent for shapes between 200 and 225). The shape argument is the concentration of a Gamma leaf, with rate * x as the second argument, and about x for a Poisson leaf, with the rate as the second argument. Where the power series of torch for the lower incomplete gamma function stops before it has converged (a shape above about 3e5 and a second argument more than 4.5 standard deviations below it), a uniform asymptotic expansion is used instead. For shape arguments above 1e7 the error grows with the shape: for a Gamma leaf to about 4e-10 at 1e10, 5e-9 at 1e12 and 7e-8 at 4e14; for a Poisson leaf, whose atom loses digits in addition, to about 2e-9 at 1e9, 1e-7 at 1e12 and 7e-6 at 4e14. Binomial and Hypergeometric leaves build a table of the probability mass function over their support in every call, with a size proportional to the largest support. The relative error of these two families is about 1e-15 times the largest count (the number of trials or the population size): about 4e-12 for a count of 1e4 and 6e-10 for a count of 1e6. In all other cases the relative error is well below 1e-9. A Histogram leaf stores its bin edges in float32, so its p-values refer to the rounded edges; its bin probabilities are softmax(logits).

Parameters:
  • leaf (LeafModule) – Leaf module of a supported family: Normal, LogNormal, Exponential, Gamma, Laplace, Uniform, Histogram, Bernoulli, Categorical, Poisson, Geometric (number of failures before the first success), Binomial or Hypergeometric.

  • x (Tensor) – Observed values of shape (N, F): the columns of the leaf in the order of leaf.scope.query, without NaN. The caller handles missing values and masks the result. The tensor is cast to float64 and moved to the device of the leaf.

  • side (Literal['both', 'left', 'right']) – Test side. "left" rejects small values, "right" rejects large values and "both" rejects values in either tail.

  • discrete_mode (Literal['exact', 'midp', 'randomized']) – P-value definition at discrete leaves, see above.

  • uniforms (Tensor | None) – Random numbers in [0, 1) of shape (N, F), one per row and feature, shared by all channels and repetitions. Required if and only if discrete_mode is "randomized".

Return type:

Tensor

Returns:

P-values of shape (N, F, C, R) with (F, C, R) = leaf.out_shape, in float64 on the device of the leaf, clamped to [1e-300, 1] and without gradients.

Raises:
  • InvalidTypeError – If leaf is not a leaf module or x is not a real-valued tensor.

  • InvalidParameterCombinationError – If uniforms is missing in randomized mode or given in another mode.

  • InvalidParameterError – If side or discrete_mode is unknown, if uniforms is not in [0, 1), if x contains NaN, if a parameter of the leaf lies outside the supported range (a Poisson rate above 5e14, a Gamma concentration above 1e15, a number of trials of a Binomial leaf that is negative, not finite or not an integer, a count of a Hypergeometric leaf that is not finite, a Uniform leaf whose high is not larger than low or whose width high - low is infinite), or if a tail probability is NaN because the parameters of the leaf are degenerate (NaN, or a rate, scale or width that is zero or infinite in float64, which a float32 leaf reaches when the exponential of its log-parameter underflows or overflows).

  • ShapeError – If x is not (N, F), if uniforms does not have the shape of x, or if the parameters of the leaf do not have the shape (features, channels, repetitions), so that the result would not have the shape (N, F, C, R).

  • UnsupportedOperationError – If the leaf family is not supported, if the leaf is conditional or if its class overrides log_likelihood.

Goodness of Fit

spflow.zoo.mc.binomial_gof(pvalues, alpha=0.05)[source]

Test root p-values for an excess of values at or below one level (exact binomial test).

With k the number of p-values <= alpha among n, the result is the upper tail P(Bin(n, alpha) >= k). The test is one-sided: only too many small p-values count against the circuit.

A small result means that the rows are not samples of the circuit (the circuit misfits these rows). A large result is not a proof of fit. A conservative combination rule can hide a misfit but cannot cause a false alarm. This is the primary goodness-of-fit statistic, at one level alpha that is chosen before looking at the p-values. Results at several levels are not corrected for the selection of the level.

Use the p-values of held-out rows: rows that were used to fit the circuit give optimistic (too large) p-values. Pass float64 p-values: a float32 0.05 is slightly above 0.05 and is not counted at alpha = 0.05.

Parameters:
  • pvalues (Tensor | ndarray | Sequence[float]) – Root p-values of independent rows, as a tensor (any device), a NumPy array or a sequence of floats of any shape. The input is flattened and non-finite entries are removed.

  • alpha (float) – Level in the open interval (0, 1) at which the p-values are counted.

Return type:

float

Returns:

The p-value of the goodness-of-fit test, as a Python float.

Raises:
  • InvalidParameterError – If alpha is not in (0, 1), if pvalues has no finite entry or if a finite entry lies outside [0, 1].

  • InvalidTypeError – If alpha is not a real number, or if pvalues does not hold real numbers (for example strings, None or complex numbers) or cannot be converted to an array (for example a sequence of tensors that require grad).

  • ShapeError – If pvalues is a nested sequence whose parts differ in length.

spflow.zoo.mc.ks_gof(pvalues)[source]

Test root p-values against the uniform distribution (one-sided Kolmogorov-Smirnov test).

The statistic is D+ = max_i (i / n - p_(i)) with p_(i) the i-th smallest p-value. It measures how far the empirical distribution function rises above the uniform one, so the test is one-sided: only too many small p-values count against the circuit. The result is 1.0 if D+ <= 0 and otherwise the upper tail of the exact finite-sample distribution of D+ (scipy.stats.ksone). If no p-value is above 1 / n, this tail equals p_(n) ** n and is computed in that form, which keeps its relative precision when all p-values are tiny.

A small result means that the rows are not samples of the circuit (the circuit misfits these rows). A large result is not a proof of fit. A conservative combination rule can hide a misfit but cannot cause a false alarm.

The test assumes a continuous null distribution and is conservative with ties, for example many rows with p = 1 after clipping or exact p-values of discrete leaves. Treat it as the secondary statistic and binomial_gof() at one pre-chosen level as the primary one.

Use the p-values of held-out rows: rows that were used to fit the circuit give optimistic (too large) p-values. The exact distribution takes about a second for one million p-values.

Parameters:

pvalues (Tensor | ndarray | Sequence[float]) – Root p-values of independent rows, as a tensor (any device), a NumPy array or a sequence of floats of any shape. The input is flattened and non-finite entries are removed.

Return type:

float

Returns:

The p-value of the goodness-of-fit test, as a Python float.

Raises:
  • InvalidParameterError – If pvalues has no finite entry or if a finite entry lies outside [0, 1].

  • InvalidTypeError – If pvalues does not hold real numbers (for example strings, None or complex numbers) or cannot be converted to an array (for example a sequence of tensors that require grad).

  • ShapeError – If pvalues is a nested sequence whose parts differ in length.

spflow.zoo.mc.gof_report(pvalues, alphas=(0.01, 0.05, 0.1))[source]

Summarize the goodness of fit of root p-values at several levels.

The report holds ks_gof() and, for every level, the number and the rate of p-values at or below the level and binomial_gof() at the level. Both tests are one-sided against an excess of small p-values. A small value means that the rows are not samples of the circuit (the circuit misfits these rows); large values are not a proof of fit. A conservative combination rule can hide a misfit but cannot cause a false alarm.

The binomial values at the different levels are not corrected for the selection of the level. Decide on one level before looking at the report and read the binomial test at that level as the primary statistic. The Kolmogorov-Smirnov test is the secondary statistic, because it assumes a continuous null distribution and is conservative with ties (many rows with p = 1 after clipping, exact p-values of discrete leaves).

Use the p-values of held-out rows: rows that were used to fit the circuit give optimistic (too large) p-values. Pass float64 p-values: a float32 0.05 is slightly above 0.05 and is not counted at the level 0.05.

Parameters:
  • pvalues (Tensor | ndarray | Sequence[float]) – Root p-values of independent rows, as a tensor (any device), a NumPy array or a sequence of floats of any shape. The input is flattened and non-finite entries are removed.

  • alphas (Sequence[float]) – Levels in the open interval (0, 1), as a sequence. One level is (alpha,).

Return type:

dict[str, float | int]

Returns:

A flat dictionary with the keys "n" (number of finite p-values, int), "ks_gof" (float) and, for every level, "count_at_{alpha}" (int), "rate_at_{alpha}" (float) and "binomial_gof_at_{alpha}" (float). The level in a key is the shortest decimal form of the float, for example "count_at_0.05".

Raises:
  • InvalidParameterError – If a level is not in (0, 1), if pvalues has no finite entry or if a finite entry lies outside [0, 1].

  • InvalidTypeError – If alphas is a string or not iterable (for example a single number), if a level is not a real number, or if pvalues does not hold real numbers (for example strings, None or complex numbers) or cannot be converted to an array (for example a sequence of tensors that require grad).

  • ShapeError – If pvalues is a nested sequence whose parts differ in length.