Simpson.lean

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

/-
Simpson.lean. Chapter 5 section 5.5, Simpson's paradox as an aggregation quotient.

A pooled rate is the size-weighted mean of the group rates, so pooling is a quotient that
declares the group labels irrelevant. It can reverse a comparison. In the classical
example, one treatment wins in both groups and loses in the pool, because the groups have
different sizes under the two treatments. Both facts are checked here.
-/
import Mathlib

namespace DMO.Simpson

open Finset

variable {γ : Type*}

/-- The pooled rate over groups `G`, with `n g` rows and `k g` successes in group `g`. -/
noncomputable def pooled (G : Finset γ) (n k : γ → ℝ) : ℝ := (∑ g ∈ G, k g) / ∑ g ∈ G, n g

/-- The rate within a group. -/
noncomputable def rate (n k : γ → ℝ) (g : γ) : ℝ := k g / n g

/-- **Pooling is a size-weighted mean of the group rates**, the aggregation quotient. -/
theorem pooled_eq_weighted (G : Finset γ) (n k : γ → ℝ) (hn : ∀ g ∈ G, n g ≠ 0) :
    pooled G n k = ∑ g ∈ G, (n g / ∑ g' ∈ G, n g') * rate n k g := by
  unfold pooled rate
  have hterm : ∀ g ∈ G, (n g / ∑ g' ∈ G, n g') * (k g / n g) = k g / ∑ g' ∈ G, n g' := by
    intro g hg
    rw [div_mul_div_comm, mul_comm (n g), mul_div_mul_right _ _ (hn g hg)]
  rw [Finset.sum_congr rfl hterm, ← Finset.sum_div]

/-- **The reversal.** Treatment A succeeds in 81 of 87 and 192 of 263, treatment B in 234 of
270 and 55 of 80. A wins in both groups and loses in the pool. -/
theorem reversal :
    (234 : ℝ) / 270 < 81 / 87 ∧ (55 : ℝ) / 80 < 192 / 263 ∧
      (81 + 192 : ℝ) / (87 + 263) < (234 + 55) / (270 + 80) := by
  refine ⟨?_, ?_, ?_⟩ <;> norm_num

/-- The reversal needs unequal group sizes. With the same group sizes under both treatments
the pooled comparison agrees with a comparison that holds in every group. -/
theorem no_reversal_of_equal_sizes (G : Finset γ) (n kA kB : γ → ℝ) (hn : ∀ g ∈ G, 0 < n g)
    (h : ∀ g ∈ G, rate n kB g ≤ rate n kA g) :
    pooled G n kB ≤ pooled G n kA := by
  rw [pooled_eq_weighted G n kA (fun g hg => (hn g hg).ne'),
    pooled_eq_weighted G n kB (fun g hg => (hn g hg).ne')]
  apply Finset.sum_le_sum
  intro g hg
  apply mul_le_mul_of_nonneg_left (h g hg)
  have := hn g hg
  have hpos : 0 < ∑ g' ∈ G, n g' := Finset.sum_pos (fun g' hg' => hn g' hg') ⟨g, hg⟩
  positivity

end DMO.Simpson