Conformal p-values, PRDS, FDR procedures and calibration-conditional adjustments
DefinitionConformalOutlierTesting_BasicObjects of Sections 1–4 and Appendix A of Bates, Candès, Lei, Romano and Sesia, Testing for Outliers with Conformal p-values (arXiv:2104.08279v3). The training data are held fixed, so every object is a function of the scores .
- Scores and their law. There are calibration scores and test scores . Their joint law is . Here is the law of for , and is the score law of test point , with for an inlier. So the calibration scores are i.i.d., and all test scores are independent of each other and of the calibration data.
- Marginal conformal p-value (eq. 3). . The vector of test p-values is .
- Order statistics. is the sorted vector.
- PRDS (Definition 1). A set is increasing if and coordinatewise imply . A random vector is PRDS on if, for every and every measurable increasing , the conditional probability has a version that is nondecreasing in .
- FDR (eq. 7). For a rejection set and true nulls , the false discovery proportion is , and the FDR is its expectation.
- BH. , and the procedure rejects .
- Storey–BH (Appendix A.4). Let and . Let , with if no qualifies. The procedure rejects .
- Calibration-conditional adjustment (eqs. 10–11). A sequence satisfies the band condition at level if for i.i.d. uniform on . The adjustment function is .
- False positive rate (eq. 9). , as a function of the calibration scores.
- Fisher's test. The statistic is . is the -quantile of the chi-square law with degrees of freedom, which is the gamma law with shape and rate . is the -quantile of and . The conditional type-I error given is the -probability of rejection with the calibration scores fixed.
- Correlation. .
Formalization Note The test scores are modelled as independent of each other and of the calibration data, as in Section 1.1. Theorem 2 as printed asks only that the inliers be independent. Its proof assumes this full independence (see the note on Theorem 2). The Storey–BH estimate uses , as in Appendix A.4 and its proofs. The main text (Section 2.3) writes .
import Mathlib
/-!
Bates, Candès, Lei, Romano and Sesia, *Testing for Outliers with Conformal p-values*,
arXiv:2104.08279v3: marginal conformal p-values (Section 1.1, eq. (3)), positive regression
dependence (Section 2.2, Definition 1), the false discovery rate with the Benjamini–Hochberg and
Storey–BH procedures (Section 2.2, eq. (7); Appendix A.4), calibration-conditional adjustments
(Section 3.2, eqs. (10)–(11)), the pointwise false positive rate (Section 3.1, eq. (9)) and the
quantities of Fisher's combination test (Section 2.1).
The training data are treated as fixed (Section 1.1), so every object is a function of the scores
`ŝ(X_i)`: calibration scores `s : Fin n → ℝ` and test scores `t : Fin m → ℝ`.
-/
open MeasureTheory ProbabilityTheory
noncomputable section
namespace ConformalOutlierTesting
variable {n m : ℕ}
/-- Section 1.1, eq. (3): the marginal conformal p-value of a test score `x` given calibration
scores `s₁, …, sₙ`, `û^(marg)(x) = (1 + |{i : sᵢ ≤ x}|) / (n + 1)`. -/
def margPval (s : Fin n → ℝ) (x : ℝ) : ℝ :=
(1 + ((Finset.univ.filter fun i => s i ≤ x).card : ℝ)) / (n + 1)
/-- The order statistics `s₍₁₎ ≤ ⋯ ≤ s₍ₙ₎` of a vector, indexed from `0`: `orderStat s k = s₍ₖ₊₁₎`
(Section 3.2, Theorem 4; Appendix A.3, `Z = (S₍₁₎, …, S₍ₙ₎)`). -/
def orderStat (s : Fin n → ℝ) : Fin n → ℝ :=
s ∘ Tuple.sort s
/-- Section 1.1 and Theorem 2: the joint law of the calibration scores and the test scores. The
`n` calibration scores are i.i.d. with law `μ` (the law of `ŝ(X)` for `X ∼ P_X`), the `m` test
scores are independent of them and of each other, and test point `j` has score law `ν j`
(equal to `μ` for an inlier). -/
def scoreLaw (μ : Measure ℝ) (ν : Fin m → Measure ℝ) :
Measure ((Fin n → ℝ) × (Fin m → ℝ)) :=
(Measure.pi fun _ : Fin n => μ).prod (Measure.pi ν)
/-- Section 2.2: the vector `(û^(marg)(X_{2n+1}), …, û^(marg)(X_{2n+m}))` of marginal conformal
p-values of the test points, as a function of (calibration scores, test scores). -/
def margPvals (ω : (Fin n → ℝ) × (Fin m → ℝ)) : Fin m → ℝ :=
fun j => margPval ω.1 (ω.2 j)
/-- Section 2.2, Definition 1: a random vector `X = (X₁, …, X_m)` is PRDS on `I₀` if for every
`i ∈ I₀` and every (measurable) increasing set `A`, `P[X ∈ A | X_i = x]` is nondecreasing in `x`,
i.e. this conditional probability has a nondecreasing version `f(x)`. -/
def IsPRDS {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) (X : Ω → Fin m → ℝ)
(I₀ : Finset (Fin m)) : Prop :=
∀ i ∈ I₀, ∀ A : Set (Fin m → ℝ), IsUpperSet A → MeasurableSet A →
∃ f : ℝ → ℝ, Monotone f ∧
(fun ω => f (X ω i)) =ᵐ[P]
condExp (MeasurableSpace.comap (fun ω => X ω i) inferInstance) P
((X ⁻¹' A).indicator fun _ => (1 : ℝ))
/-- Section 2.2, eq. (7): the false discovery proportion `|R ∩ H₀| / max{1, |R|}` of a rejection
set `R` when the true nulls are `H₀`. -/
def fdp (R H₀ : Finset (Fin m)) : ℝ :=
((R ∩ H₀).card : ℝ) / max 1 (R.card : ℝ)
/-- Section 2.2, eq. (7): the false discovery rate `E[|R ∩ H₀| / max{1, |R|}]` of a random
rejection set. -/
def fdr {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) (rej : Ω → Finset (Fin m))
(H₀ : Finset (Fin m)) : ℝ :=
∫ ω, fdp (rej ω) H₀ ∂P
/-- Section 2.2 (Corollary 1) and Section 3.6.4: the number of BH rejections at level `α`,
`R(α) = max{r ∈ {0, …, m} : |{i : p_i ≤ rα/m}| ≥ r}`. -/
def bhCount (α : ℝ) (p : Fin m → ℝ) : ℕ :=
((Finset.range (m + 1)).filter fun r : ℕ =>
r ≤ (Finset.univ.filter fun i => p i ≤ ((r : ℕ) : ℝ) * α / m).card).sup id
/-- Section 2.2 (Corollary 1) and Section 3.6.4: the BH procedure at level `α` rejects every
hypothesis with `p_i ≤ α R(α) / m`. -/
def bhRej (α : ℝ) (p : Fin m → ℝ) : Finset (Fin m) :=
Finset.univ.filter fun i => p i ≤ (bhCount α p : ℝ) * α / m
/-- Appendix A.4: `A = Σᵢ I(p_i ≥ λ)`, the number of p-values at least `λ`. -/
def storeyA (lam : ℝ) (p : Fin m → ℝ) : ℕ :=
(Finset.univ.filter fun i => lam ≤ p i).card
/-- Appendix A.4: Storey's estimate `π̂₀ = (1 + A) / (m (1 - λ))` of the proportion of nulls. -/
def storeyPi0 (lam : ℝ) (p : Fin m → ℝ) : ℝ :=
(1 + (storeyA lam p : ℝ)) / (m * (1 - lam))
/-- Appendix A.4: `R = max{r : p₍ᵣ₎ ≤ α r / (m π̂₀), p₍ᵣ₎ < λ}` (and `R = 0` if no `r ∈ {1, …, m}`
qualifies); the index `r : Fin m` stands for `r + 1`. -/
def storeyCount (α lam : ℝ) (p : Fin m → ℝ) : ℕ :=
(Finset.univ.filter fun r : Fin m =>
orderStat p r ≤ α * ((r : ℕ) + 1 : ℝ) / (m * storeyPi0 lam p) ∧ orderStat p r < lam).sup
fun r => (r : ℕ) + 1
/-- Section 2.3 and Appendix A.4: the rejection set of the Storey–BH procedure,
`R = {i : p_i ≤ α R / (m π̂₀), p_i < λ}`. -/
def storeyRej (α lam : ℝ) (p : Fin m → ℝ) : Finset (Fin m) :=
Finset.univ.filter fun i =>
p i ≤ α * (storeyCount α lam p : ℝ) / (m * storeyPi0 lam p) ∧ p i < lam
/-- Section 3.2, Theorem 4: the uniform law on `[0, 1]`. -/
def unifLaw : Measure ℝ :=
(volume : Measure ℝ).restrict (Set.Icc 0 1)
/-- Section 3.2, Theorem 4, eq. (10): `b₀ = 0`, `b_{n+1} = 1`, `0 ≤ b₁ ≤ ⋯ ≤ bₙ ≤ 1`, and for
`U₁, …, Uₙ` i.i.d. uniform on `[0, 1]`, `P[U₍₁₎ ≤ b₁, …, U₍ₙ₎ ≤ bₙ] ≥ 1 - δ`. -/
def IsCCVSequence (n : ℕ) (δ : ℝ) (b : ℕ → ℝ) : Prop :=
b 0 = 0 ∧ b (n + 1) = 1 ∧ (∀ i, 1 ≤ i → i ≤ n → 0 ≤ b i ∧ b i ≤ 1) ∧
(∀ i, 1 ≤ i → i < n → b i ≤ b (i + 1)) ∧
ENNReal.ofReal (1 - δ) ≤
(Measure.pi fun _ : Fin n => unifLaw) {u | ∀ k : Fin n, orderStat u k ≤ b ((k : ℕ) + 1)}
/-- Section 3.2, Theorem 4, eq. (11): the piecewise-constant adjustment function
`h(t) = b_{⌈(n+1)t⌉}`, `t ∈ [0, 1]`. -/
def adjFun (b : ℕ → ℝ) (n : ℕ) (t : ℝ) : ℝ :=
b ⌈((n : ℝ) + 1) * t⌉₊
/-- Section 3.1, eq. (9): the conditional false positive rate
`FPR(α; D) = P[û^(marg)(X_{2n+1}) ≤ α | D]` of an inlier test point whose score has law `μ`, as a
function of the calibration scores. -/
def fpr (μ : Measure ℝ) (s : Fin n → ℝ) (α : ℝ) : ℝ :=
(μ {x | margPval s x ≤ α}).toReal
/-- Section 2.1: the `q`-quantile `inf{x : F_ν(x) ≥ q}` of a law `ν` on `ℝ`. -/
def quantile (ν : Measure ℝ) (q : ℝ) : ℝ :=
sInf {x | q ≤ cdf ν x}
/-- Section 2.1: the chi-square law with `k` degrees of freedom, the gamma law with shape `k/2`
and rate `1/2`. -/
def chiSqLaw (k : ℕ) : Measure ℝ :=
gammaMeasure ((k : ℝ) / 2) (1 / 2)
/-- Section 2.1: the standard normal law `N(0, 1)`. -/
def stdNormal : Measure ℝ :=
gaussianReal 0 1
/-- Section 2.1, Theorem 1: the survival function `Φ̄(x) = 1 - Φ(x)` of `N(0, 1)`. -/
def normSurv (x : ℝ) : ℝ :=
1 - cdf stdNormal x
/-- Section 2.1: Fisher's combination statistic `-2 Σᵢ log û^(marg)(X_{2n+i})` of the test
scores `t` given calibration scores `s`. -/
def fisherStat (s : Fin n → ℝ) (t : Fin m → ℝ) : ℝ :=
-2 * ∑ i, Real.log (margPval s (t i))
/-- Section 2.1, Theorem 1, eq. (5): under the global null, the conditional type-I error
`P[-2 Σᵢ log û^(marg)(X_{2n+i}) ≥ χ²(2m; 1-α) | D]` of Fisher's combination test, as a function of
the calibration scores (the `m` test scores are i.i.d. with law `μ`, independent of `D`). -/
def condFisherRejProb (μ : Measure ℝ) (m : ℕ) (α : ℝ) (s : Fin n → ℝ) : ℝ :=
((Measure.pi fun _ : Fin m => μ)
{t | quantile (chiSqLaw (2 * m)) (1 - α) ≤ fisherStat s t}).toReal
/-- Section 2.1, Lemma 1: the correlation `Cor[X, Y] = Cov[X, Y] / √(Var X · Var Y)`. -/
def corr {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) (X Y : Ω → ℝ) : ℝ :=
covariance X Y P / Real.sqrt (variance X P * variance Y P)
end ConformalOutlierTesting
Read-back
What the Lean code literally says, in plain math · claude-opus-5-5
margPval (marginal conformal p-value). Let , let be calibration scores, and let . The value is
The count uses the non-strict inequality , so the value increases with : more calibration scores at or below give a larger p-value. The value always lies in and is strictly positive. When it equals for every .
orderStat (order statistics). For , this is the vector , the entries of rearranged in nondecreasing order. It is indexed from , so entry is , the -th smallest entry. Tied values are repeated according to their multiplicity. When it is the empty vector.
scoreLaw (joint law of the scores). Given a measure on and measures on , this is the product measure on :
- The first factor is the law of the calibration vector .
- The second factor is the law of the test vector .
The definition places no requirement that or the be probability measures (or even finite). It builds the product measure from whatever measures are supplied.
margPvals (vector of test p-values). For a pair with and , this is the vector in whose -th entry is
This is the marginal conformal p-value above, applied to test score with calibration scores .
IsPRDS (positive regression dependence on a subset). Let be a measurable space with an arbitrary measure , which is not required to be a probability measure. Let be a function, not assumed measurable, and let . The property holds when, for every and every measurable upper set , there is a nondecreasing function such that, for -almost every ,
- An upper set is taken in the coordinatewise order: if and in every coordinate, then .
- is the -algebra generated by the -th coordinate .
Degenerate cases:
- If , the property holds vacuously.
- The conditional expectation is the library's: it is defined to be whenever its prerequisites fail. This happens, for example, if or is not measurable (so is not contained in the ambient -algebra, or the indicator is not integrable), or if is not -finite on . In those situations works and the property holds trivially.
- only needs to match on the range of , up to -null sets. Elsewhere it is unconstrained apart from being nondecreasing.
fdp (false discovery proportion). For finite sets , the value is
It equals when , and it always lies in .
fdr (false discovery rate). Let be a measurable space with an arbitrary measure . Let assign a subset of to each outcome, and let . The value is the integral
This is the (Bochner) integral, which is set to whenever the integrand is not -integrable. That happens, for example, if is not measurable, or if is an infinite measure and the integrand is not integrable. is not required to be a probability measure. When is one and the integrand is measurable, the value lies in .
bhCount (number of Benjamini–Hochberg rejections). For , which is not restricted in sign or size, and , the value is
- always qualifies, so the maximum exists and .
- When , the quotient is taken to be and .
- The are arbitrary reals and need not lie in .
bhRej (Benjamini–Hochberg rejection set). For and , the set is
with as in bhCount. If (or ), the threshold is . In that case every with is still included, which can only occur when .
storeyA. For and , this is the count
storeyPi0 (Storey's null-proportion estimate). For and , the value is
with as in storeyA. There is no restriction on :
- If or , the denominator is and the value is defined to be .
- If , the value is negative.
storeyCount (number of Storey–BH rejections). For and , let be the sorted entries of . The value is the largest satisfying both
and if no such exists. When , the right-hand side of the first condition is defined to be . This covers the cases and . When and , we have .
storeyRej (Storey–BH rejection set). For and , the set is
with from storeyCount and from storeyPi0. If , the first threshold is .
unifLaw (uniform law on ). This is Lebesgue measure on restricted to the closed interval . It is a probability measure.
IsCCVSequence (calibration-conditional adjustment sequence). Given , and a sequence of reals indexed by all of , the property holds when all of the following are true:
- and ;
- for ;
- for , so that ;
- with i.i.d. uniform on and order statistics ,
Edge cases:
- The values for are unconstrained.
- If , the probability condition holds trivially.
- If , it is impossible to satisfy, since the probability is at most .
- For , the event is certain, so the condition reduces to , together with and .
adjFun (piecewise-constant adjustment function). For a sequence , and , the value is
where is the smallest natural number , taken to be when . The argument is not restricted to :
- For the value is .
- For the index exceeds , and the value is whatever the sequence holds there.
fpr (conditional false positive rate). For a measure on , which is not required to be a probability measure, calibration scores and , the value is
where . It is converted to a real number, and it is if this measure is infinite.
quantile. For a measure on and , the value is
- is the library's cumulative distribution function. It equals when is a probability measure; for other measures it is a library-defined default function rather than 's distribution function.
- The infimum of a real set is taken to be when the set is empty or unbounded below. Hence the value is when (the set is all of ), when , and whenever the level is never reached. The last case includes for laws whose distribution function never attains .
chiSqLaw (chi-square law). For , this is the gamma law with shape and rate , which has density for and for . For the shape is . The library takes and division by to give , so the density is identically zero and the result is the zero measure, not a probability measure.
stdNormal. This is the standard normal law on .
normSurv. For , the value is , where is the cumulative distribution function of .
fisherStat (Fisher's combination statistic). For calibration scores and test scores , the value is
- Each lies in , so the logarithms are well defined and the statistic is always .
- It equals when .
condFisherRejProb (conditional rejection probability of Fisher's test). Let be a measure on (not required to be a probability measure), , , and . Let , with the quantile and the law as defined above. The value is
converted to a real number, and if this measure is infinite. Edge cases:
- . Then , so and the event is all of , because the statistic is always .
- . Then . For the chi-square distribution function never reaches , so again and the event is all of .
- . The chi-square law is the zero measure and the statistic is , so the value is if and otherwise.
corr (correlation). Let be a measurable space with an arbitrary measure , and let . The value is
- Covariance and variance are the library's integral-based notions, centred at and .
- Any integral of a non-integrable function is taken to be , and an infinite variance is converted to .
- If either variance is (including these junk cases), the denominator is and the value is defined to be .
- is not required to be a probability measure.
Confirmed by the mission captain (proposal self-audit).
Confirmed by the moderator at approval.