"""P-value combination rules for Membership Circuits.
A combination rule merges the p-values of the children of one circuit node into the p-value of that
node. Rules come in two roles. A :class:`SumCombination` is valid at sum nodes, where the children
share one scope and only the p-value of the mixture component that generated the row is known to be
valid. A :class:`ProductCombination` is valid at product nodes, where the children have disjoint
scopes. The two abstract classes carry this validity license: a rule must not be used in a role it
does not inherit from.
All rules share one tensor convention: the children of a node lie on the last axis and all leading
axes broadcast.
"""
from __future__ import annotations
import math
from abc import ABC, abstractmethod
from collections.abc import Callable
from dataclasses import dataclass
import torch
from torch import Tensor
from spflow.exceptions import InvalidParameterError, InvalidTypeError, ShapeError
from spflow.meta.data.scope import Scope
from spflow.modules.module import Module
from spflow.zoo.mc.constants import (
constant_table,
harmonic_mean_multiplier,
harmonic_number,
harmonic_star_inv_c,
harmonic_star_inv_d,
)
# Lower limit of an input inside a logarithm or a reciprocal. Leaf p-values never fall below it, but
# an inner node can return an exact zero.
_INPUT_FLOOR = 1e-300
# Relative slack of the validity check of WeightedArithmeticMean. Rounding alone leaves valid
# coefficients short by up to 1e-15, so an exact comparison would reject them.
_VALIDITY_RTOL = 1e-9
# GridHarmonic: number of bisection steps, relative lowering of the lower end of the bisection and
# rounding allowance per child in the test "sum of unit fractions >= 1".
_GRID_STEPS = 56
_GRID_LOWER_SLACK = 1e-12
_GRID_SUM_SLACK = 4.0 * 2.2e-16
[docs]
@dataclass(frozen=True)
class SumNodeContext:
"""Read-only information about the sum nodes that a coefficient function serves.
Attributes:
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.
"""
num_children: int
module: Module | None = None
scope: Scope | None = None
CoefficientFunction = Callable[[Tensor, SumNodeContext], tuple[Tensor, Tensor]]
[docs]
class PValueCombination(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).
Attributes:
name: Stable short identifier of the rule, used in configuration names.
"""
name: str
[docs]
@abstractmethod
def combine(
self,
p: Tensor,
*,
weights: Tensor | None = None,
observed: Tensor | None = None,
context: SumNodeContext | None = None,
) -> Tensor:
"""Merge the p-values of the children of each node.
Args:
p: Child p-values with the children on the last axis, shape ``(..., K)``. The tensor is
not modified.
weights: 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: 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 :class:`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: Information about the sum nodes for coefficient functions. Used by sum rules
only.
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.
"""
def __repr__(self) -> str:
return f"{self.__class__.__name__}(name={self.name!r})"
[docs]
class SumCombination(PValueCombination, ABC):
"""Abstract base class of the rules that are valid at sum nodes."""
[docs]
class ProductCombination(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]``.
"""
def _expand_observed(observed: Tensor | None, p: Tensor) -> Tensor:
"""Return the mask in the shape of ``p``; ``None`` stands for a mask that is ``True`` everywhere."""
if observed is None:
return torch.ones_like(p, dtype=torch.bool)
if observed.dtype != torch.bool:
raise InvalidTypeError(f"observed must be a boolean tensor, got dtype {observed.dtype}.")
try:
return observed.expand(p.shape)
except RuntimeError as error:
raise ShapeError(
f"observed with shape {tuple(observed.shape)} does not broadcast to p with shape "
f"{tuple(p.shape)}."
) from error
def _require_children_axis(p: Tensor) -> None:
"""Raise unless the last axis of ``p`` holds at least one child."""
if p.dim() == 0 or p.shape[-1] == 0:
raise ShapeError(f"p needs a non-empty children axis as its last axis, got shape {tuple(p.shape)}.")
def _prepare(p: Tensor, observed: Tensor | None) -> tuple[Tensor, Tensor, Tensor]:
"""Return the detached ``float64`` p-values, the expanded mask and the number of observed children."""
_require_children_axis(p)
p = p.detach().to(torch.float64)
observed = _expand_observed(observed, p)
return p, observed, observed.sum(-1)
def _sum_node_shape(p: Tensor, weights: Tensor) -> torch.Size:
"""Return the shape of a sum-node result: the broadcast of the leading axes of ``p`` and ``weights``."""
_require_children_axis(p)
if weights.dim() == 0 or p.shape[-1] != weights.shape[-1]:
raise ShapeError(
"p and weights need the same number of children on the last axis, got shapes "
f"{tuple(p.shape)} and {tuple(weights.shape)}."
)
try:
return torch.Size(torch.broadcast_shapes(p.shape[:-1], weights.shape[:-1]))
except RuntimeError as error:
raise ShapeError(
f"The leading axes of p with shape {tuple(p.shape)} and of weights with shape "
f"{tuple(weights.shape)} do not broadcast."
) from error
def _sort_observed(p: Tensor, observed: Tensor) -> Tensor:
"""Sort the children in ascending order; unobserved entries become ``+inf`` and sort last."""
return torch.sort(torch.where(observed, p, math.inf), dim=-1).values
def _simes(p_sorted: Tensor, k_obs: Tensor) -> Tensor:
"""Return ``min_i (k / i) * p_(i)`` over the ``k = k_obs`` smallest entries; ``+inf`` for ``k = 0``."""
rank = torch.arange(1, p_sorted.shape[-1] + 1, dtype=p_sorted.dtype, device=p_sorted.device)
k = k_obs.unsqueeze(-1)
used = rank <= k
# The inner ``where`` keeps the placeholder +inf out of the product: 0 * inf is NaN for k = 0.
terms = k.to(p_sorted.dtype) / rank * torch.where(used, p_sorted, 1.0)
return torch.where(used, terms, math.inf).amin(-1)
[docs]
class MaxP(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.
"""
name = "maxP"
[docs]
def combine(
self,
p: Tensor,
*,
weights: Tensor | None = None,
observed: Tensor | None = None,
context: SumNodeContext | None = None,
) -> Tensor:
"""Return the maximum of the observed child p-values of each node.
Args:
p: Child p-values with the children on the last axis, shape ``(..., K)``.
weights: 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: Boolean mask, broadcastable to ``p``. ``None`` means that all entries are
observed.
context: Ignored.
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``.
"""
p, observed, k_obs = _prepare(p, observed)
out = torch.where(observed, p, -math.inf).amax(-1)
out = torch.where(k_obs == 0, 1.0, out)
if weights is None:
return out
return out.expand(_sum_node_shape(p, weights))
[docs]
class WeightedArithmeticMean(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 :meth:`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.
Attributes:
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 :meth:`combine` tests the validity condition.
"""
[docs]
def __init__(self, coefficients: CoefficientFunction, name: str, check_validity: bool = True) -> None:
"""Initialize the rule.
Args:
coefficients: Function ``(weights, context) -> (a, c)``, see the class documentation.
name: Stable short identifier of the rule, used in configuration names.
check_validity: If ``True``, :meth:`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.
"""
if not callable(coefficients):
raise InvalidTypeError(f"coefficients must be callable, got {type(coefficients).__name__}.")
if not isinstance(name, str):
raise InvalidTypeError(f"name must be a string, got {type(name).__name__}.")
if not name:
raise InvalidParameterError("name must not be empty.")
self.coefficients = coefficients
self.name = name
self.check_validity = check_validity
[docs]
def combine(
self,
p: Tensor,
*,
weights: Tensor | None = None,
observed: Tensor | None = None,
context: SumNodeContext | None = None,
) -> Tensor:
"""Return ``c * sum_i a_i * p_i`` for each sum node.
Args:
p: Child p-values with the children on the last axis, shape ``(..., K)``.
weights: Normalized mixture weights of shape ``(..., K)``. Required.
observed: 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: Information about the sum nodes for the coefficient function. Defaults to
``SumNodeContext(num_children=K)``.
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]``.
"""
if weights is None:
raise InvalidParameterError(
f"The sum rule '{self.name}' needs the mixture weights of the sum nodes."
)
p = p.detach().to(torch.float64)
weights = weights.detach().to(torch.float64)
# Only the shape check is needed here: the einsum below broadcasts the leading axes itself.
_sum_node_shape(p, weights)
if context is None:
context = SumNodeContext(num_children=weights.shape[-1])
a, c = self._evaluate_coefficients(weights, context)
if self.check_validity:
self._check_validity(weights, a, c)
out = c * torch.einsum("...k,...k->...", p, a)
if observed is None:
return out
return torch.where(_expand_observed(observed, p).any(-1), out, 1.0)
def _evaluate_coefficients(self, weights: Tensor, context: SumNodeContext) -> tuple[Tensor, Tensor]:
"""Call the coefficient function and check the types and shapes of ``a`` and ``c``."""
result = self.coefficients(weights, context)
# Checked before the unpacking, which would raise a builtin error for anything but a pair.
if not isinstance(result, tuple) or len(result) != 2:
got = f"a tuple of length {len(result)}" if isinstance(result, tuple) else type(result).__name__
raise InvalidTypeError(
f"The coefficient function of '{self.name}' must return a tuple (a, c) of two tensors, got "
f"{got}."
)
a, c = result
if not isinstance(a, Tensor) or not isinstance(c, Tensor):
raise InvalidTypeError(
f"The coefficient function of '{self.name}' must return two tensors, got "
f"{type(a).__name__} and {type(c).__name__}."
)
if a.shape != weights.shape or c.shape != weights.shape[:-1]:
raise ShapeError(
f"The coefficient function of '{self.name}' must return a with shape {tuple(weights.shape)} "
f"and c with shape {tuple(weights.shape[:-1])}, got {tuple(a.shape)} and {tuple(c.shape)}."
)
return a.detach().to(torch.float64), c.detach().to(torch.float64)
def _check_validity(self, weights: Tensor, a: Tensor, c: Tensor) -> None:
"""Raise unless ``a >= 0``, ``c > 0`` and ``c >= sum_i w_i / a_i`` over the positive weights."""
if not bool((torch.isfinite(a) & (a >= 0)).all()):
raise InvalidParameterError(
f"The coefficients a of '{self.name}' must be finite and non-negative."
)
if not bool((torch.isfinite(c) & (c > 0)).all()):
raise InvalidParameterError(f"The constant c of '{self.name}' must be finite and positive.")
positive = weights > 0
# A child with weight zero never generates a row and puts no condition on a. A coefficient of
# zero at a positive weight gives an infinite requirement and fails.
required = torch.where(positive, weights / torch.where(positive, a, 1.0), 0.0).sum(-1)
# Written as "not all(>=)", so that a NaN on either side fails the check.
if not bool((c * (1.0 + _VALIDITY_RTOL) >= required).all()):
raise InvalidParameterError(
f"The coefficients of '{self.name}' do not give a valid test at sum nodes: c must be at "
"least sum_i w_i / a_i over the children with a positive weight. Pass "
"check_validity=False only if a different null hypothesis is intended."
)
[docs]
def am_k_coefficients(weights: Tensor, context: SumNodeContext) -> tuple[Tensor, Tensor]:
"""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``.
Args:
weights: Normalized mixture weights with the children on the last axis, shape ``(..., K)``.
context: Information about the sum nodes; ``context.num_children`` is ``K``.
Returns:
Tuple ``(a, c)`` with ``a`` of shape ``(..., K)`` and ``c`` of shape ``(...)``.
"""
return weights, weights.new_full(weights.shape[:-1], float(context.num_children))
[docs]
def am_sqrtw_coefficients(weights: Tensor, context: SumNodeContext) -> tuple[Tensor, Tensor]:
"""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.
Args:
weights: Normalized mixture weights with the children on the last axis, shape ``(..., K)``.
context: Information about the sum nodes. Not used.
Returns:
Tuple ``(a, c)`` with ``a`` of shape ``(..., K)`` and ``c`` of shape ``(...)``.
"""
root = weights.sqrt()
total = root.sum(-1)
return root / total.unsqueeze(-1), total * total
[docs]
class ArithmeticMeanK(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 :class:`WeightedArithmeticMean` with
:func:`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.
"""
[docs]
def __init__(self) -> None:
"""Initialize the rule with the name ``"AMean_K"``."""
super().__init__(am_k_coefficients, name="AMean_K")
[docs]
class ArithmeticMeanSqrtW(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
:class:`WeightedArithmeticMean` with :func:`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.
"""
[docs]
def __init__(self) -> None:
"""Initialize the rule with the name ``"AMean_sqrtW"``."""
super().__init__(am_sqrtw_coefficients, name="AMean_sqrtW")
class _ProductRule(ProductCombination, ABC):
"""Product rule that is given by a formula for two or more observed children.
:meth:`combine` holds what all these rules share: a row with one observed child returns the
p-value of that child unchanged, a row without an observed child returns 1, and a row with a NaN
at an observed child returns NaN.
"""
def combine(
self,
p: Tensor,
*,
weights: Tensor | None = None,
observed: Tensor | None = None,
context: SumNodeContext | None = None,
) -> Tensor:
"""Merge the p-values of the observed children of each product node.
Per row the rule is applied to the observed children only, with their number ``k_obs`` in
place of ``K`` in every constant of the formula.
Args:
p: Child p-values in ``[0, 1]`` with the children on the last axis, shape ``(..., K)``.
weights: Ignored.
observed: Boolean mask, broadcastable to ``p``. Values of ``p`` where the mask is
``False`` are arbitrary. ``None`` means that all entries are observed.
context: Ignored.
Returns:
Merged p-values in ``float64`` with shape ``p.shape[:-1]``, not clipped unless the formula
of the rule contains the clip. A row with one observed child gives the p-value of that
child unchanged; 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`` does not broadcast to ``p``.
"""
p, observed, k_obs = _prepare(p, observed)
out = self._merge(p, observed, k_obs)
# A NaN at an observed child is an error of the caller and must stay visible. The formulas do
# not all pass it on: a sort puts it behind the placeholders of the unobserved children, and
# HarmonicMeanStar replaces it by a neutral value.
out = torch.where((observed & torch.isnan(p)).any(-1), math.nan, out)
# With one observed child the masked sum is that child's p-value, bit for bit.
single = torch.where(observed, p, 0.0).sum(-1)
out = torch.where(k_obs == 1, single, out)
return torch.where(k_obs == 0, 1.0, out)
@abstractmethod
def _merge(self, p: Tensor, observed: Tensor, k_obs: Tensor) -> Tensor:
"""Apply the formula of the rule to the observed children.
Args:
p: Child p-values in ``float64``, shape ``(..., K)``.
observed: Boolean mask with the shape of ``p``.
k_obs: Number of observed children per row, shape ``(...)``.
Returns:
Merged p-values of shape ``(...)``. Rows with fewer than two observed children may hold
any value, including NaN: :meth:`combine` overwrites them.
"""
[docs]
class Fisher(_ProductRule):
"""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 = "Fish"
def _merge(self, p: Tensor, observed: Tensor, k_obs: Tensor) -> Tensor:
half_statistic = -torch.where(observed, torch.log(p.clamp_min(_INPUT_FLOOR)), 0.0).sum(-1)
# gammaincc(0, 0) is NaN; rows without an observed child are overwritten by combine().
upper_tail: Tensor = torch.special.gammaincc(k_obs.clamp_min(1).to(p.dtype), half_statistic)
return upper_tail
[docs]
class Bonferroni(_ProductRule):
"""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 = "Bonf"
def _merge(self, p: Tensor, observed: Tensor, k_obs: Tensor) -> Tensor:
return k_obs.to(p.dtype) * torch.where(observed, p, math.inf).amin(-1)
[docs]
class Simes(_ProductRule):
"""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 :class:`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 = "Simes"
def _merge(self, p: Tensor, observed: Tensor, k_obs: Tensor) -> Tensor:
return _simes(_sort_observed(p, observed), k_obs)
[docs]
class HarmonicMean(_ProductRule):
"""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)``
(:func:`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 = "HMean_ada2"
def _merge(self, p: Tensor, observed: Tensor, k_obs: Tensor) -> Tensor:
multiplier = constant_table(
harmonic_mean_multiplier, p.shape[-1], dtype=p.dtype, device=p.device, counts=k_obs
)
reciprocal_sum = torch.where(observed, p.clamp_min(_INPUT_FLOOR).reciprocal(), 0.0).sum(-1)
return multiplier[k_obs] * k_obs.to(p.dtype) / reciprocal_sum
[docs]
class HarmonicMeanStar(_ProductRule):
"""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 :class:`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 :class:`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, :class:`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 = "HMean_star"
def _merge(self, p: Tensor, observed: Tensor, k_obs: Tensor) -> Tensor:
num_children = p.shape[-1]
inv_c = constant_table(
harmonic_star_inv_c, num_children, dtype=p.dtype, device=p.device, counts=k_obs
)[k_obs]
inv_d = constant_table(
harmonic_star_inv_d, num_children, dtype=p.dtype, device=p.device, first=3, fill=0.0, counts=k_obs
)[k_obs]
p_sorted = _sort_observed(p, observed)
smallest = p_sorted[..., 0]
# The term m = 1 as a product: exact for k = 2 and safe for inputs whose reciprocal overflows.
first = smallest * inv_c
m = torch.arange(1, num_children + 1, dtype=p.dtype, device=p.device)
k = k_obs.unsqueeze(-1)
reciprocal_sums = torch.cumsum(torch.where(p_sorted > 0, p_sorted, 1.0).reciprocal(), dim=-1)
# For k <= 2 only the term m = 1 exists.
used = (m >= 2) & (m <= k) & (k >= 3) & torch.isfinite(reciprocal_sums)
terms = (inv_c.unsqueeze(-1) + (m - 1.0) * inv_d.unsqueeze(-1)) / reciprocal_sums
later = torch.where(used, terms, math.inf).amin(-1)
out = torch.minimum(first, later).clamp_max(1.0)
return torch.where(smallest == 0, 0.0, out)
[docs]
class GridHarmonic(_ProductRule):
"""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 :class:`HarmonicMean` or :class:`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
:class:`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 = "HMean_grid"
def _merge(self, p: Tensor, observed: Tensor, k_obs: Tensor) -> Tensor:
harmonic = constant_table(harmonic_number, p.shape[-1], dtype=p.dtype, device=p.device, counts=k_obs)[
k_obs
]
p_sorted = _sort_observed(p, observed)
has_zero = p_sorted[..., 0] == 0
hommel = harmonic * _simes(p_sorted, k_obs)
# For up to three children Hommel's bound is the result. An exact zero has no logarithm to
# bisect on; its result is set below.
active = (k_obs >= 4) & ~has_zero
out = hommel
if bool(active.any()):
out = torch.where(active, self._bisect(p, observed, k_obs, harmonic, hommel, active), hommel)
return torch.where(has_zero, 0.0, out.clamp_max(1.0))
@staticmethod
def _bisect(
p: Tensor, observed: Tensor, k_obs: Tensor, harmonic: Tensor, hommel: Tensor, active: Tensor
) -> Tensor:
"""Return the upper end of the bisection on ``log(eps)``; only the rows in ``active`` are used."""
k = k_obs.to(p.dtype)
reciprocal_sum = torch.where(observed, p.reciprocal(), 0.0).sum(-1)
# l_k * (harmonic mean) is a lower bound of the result that equal inputs attain. It is lowered
# a little, so that rounding cannot place the lower end above the result. Rows that are not
# active get the harmless bracket [1, 1].
lower = torch.where(active, harmonic * k / reciprocal_sum * (1.0 - _GRID_LOWER_SLACK), 1.0)
upper = torch.where(active, hommel, 1.0)
scaled = torch.where(observed, harmonic.unsqueeze(-1) * p, math.inf)
numerator = k.unsqueeze(-1) * scaled
threshold = 1.0 - _GRID_SUM_SLACK * k
# One buffer for all steps: the plain expression allocates four temporaries per step.
fractions = torch.empty_like(scaled)
for _ in range(_GRID_STEPS):
# exp of the mean of the logs: the product lower * upper can underflow.
middle = torch.exp(0.5 * (lower.log() + upper.log()))
eps = middle.unsqueeze(-1)
torch.div(numerator, eps, out=fractions)
# The ceiling is 0 only for an exact zero input, in a row that is not active. The clamp
# keeps the division by zero out of the buffer.
fractions.ceil_().clamp_min_(1.0).reciprocal_()
fractions.masked_fill_(scaled > eps, 0.0)
inside = fractions.sum(-1) >= threshold
upper = torch.where(inside, middle, upper)
lower = torch.where(inside, lower, middle)
return upper