PValue.lean

Lean 4 source, lean/DataMiningAsObservation/PValue.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.

/-
PValue.lean. Chapter 0 section 0.9, the p-value.

Against a finite null sample, the p-value of an observation is the fraction of null draws at
least as large as it. It lies in the unit interval, it never rises as the observation
grows, and under the null, where the observation is one of the draws, the fraction of
draws whose p-value is at or below a level is at most that level. That last fact is what
makes a threshold on the p-value a false-positive rate, and what the multiple comparisons
file multiplies by the number of tests.
-/
import Mathlib

namespace DMO.PValue

open Finset

variable {ι : Type*}

/-- The p-value of the observation `x` against the null draws `S` with values `null`. -/
noncomputable def pvalue (S : Finset ι) (null : ι → ℝ) (x : ℝ) : ℝ :=
  ((S.filter fun i => x ≤ null i).card : ℝ) / S.card

/-- **In the unit interval.** -/
theorem pvalue_mem_unit (S : Finset ι) (hS : S.Nonempty) (null : ι → ℝ) (x : ℝ) :
    0 ≤ pvalue S null x ∧ pvalue S null x ≤ 1 := by
  unfold pvalue
  have hpos : (0 : ℝ) < S.card := by exact_mod_cast hS.card_pos
  refine ⟨by positivity, ?_⟩
  rw [div_le_one hpos]
  exact_mod_cast Finset.card_filter_le S _

/-- **A larger observation has a smaller p-value.** -/
theorem pvalue_antitone (S : Finset ι) (null : ι → ℝ) (x y : ℝ) (hxy : x ≤ y) :
    pvalue S null y ≤ pvalue S null x := by
  unfold pvalue
  apply div_le_div_of_nonneg_right _ (by positivity)
  exact_mod_cast Finset.card_le_card (Finset.monotone_filter_right S fun i _ h => hxy.trans h)

/-- **Under the null the p-value is at most uniform.** Ranking `n` draws, the draw ranked
`k` from the top has p-value `k / n`, and the number of draws with p-value at or below a
level `α` is at most `α n`. -/
theorem uniform_bound (n : ℕ) (α : ℝ) (hα : 0 ≤ α) :
    (((Finset.range n).filter fun k => ((k + 1 : ℕ) : ℝ) / n ≤ α).card : ℝ) ≤ α * n := by
  rcases Nat.eq_zero_or_pos n with hn | hn
  · simp [hn]
  have hn' : (0 : ℝ) < n := by exact_mod_cast hn
  have hsub : ((Finset.range n).filter fun k => ((k + 1 : ℕ) : ℝ) / n ≤ α)
      ⊆ Finset.range ⌊α * n⌋₊ := by
    intro k hk
    rw [Finset.mem_filter, Finset.mem_range] at hk
    rw [Finset.mem_range]
    have h1 : ((k + 1 : ℕ) : ℝ) ≤ α * n := by
      have := hk.2
      rwa [div_le_iff₀ hn'] at this
    have h2 : k + 1 ≤ ⌊α * n⌋₊ := Nat.le_floor h1
    omega
  calc (((Finset.range n).filter fun k => ((k + 1 : ℕ) : ℝ) / n ≤ α).card : ℝ)
      ≤ ((Finset.range ⌊α * n⌋₊).card : ℝ) := by exact_mod_cast Finset.card_le_card hsub
    _ = ⌊α * n⌋₊ := by rw [Finset.card_range]
    _ ≤ α * n := Nat.floor_le (by positivity)

end DMO.PValue