Percentile.lean
Lean 4 source, lean/DataMiningAsObservation/Percentile.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Percentile.lean. Chapter 3 section 3.5 and chapter 11 section 11.3, the percentile.
The fraction of rows at or below a value is the empirical distribution function. It is
nonnegative, at most one, nondecreasing in the value, one at or above the largest row and
zero below the smallest, and the percentile ratio the rank certificate reads, an upper
percentile over a lower one, is at least one.
-/
import Mathlib
namespace DMO.Percentile
open Finset
variable {n : ℕ}
open Classical in
/-- The fraction of rows at or below `t`. -/
noncomputable def cdf (x : Fin n → ℝ) (t : ℝ) : ℝ := ((univ.filter fun i => x i ≤ t).card : ℝ) / n
/-- **The fraction is nonnegative.** -/
theorem cdf_nonneg (x : Fin n → ℝ) (t : ℝ) : 0 ≤ cdf x t := by
unfold cdf
positivity
/-- **The fraction is at most one.** -/
theorem cdf_le_one (x : Fin n → ℝ) (t : ℝ) : cdf x t ≤ 1 := by
unfold cdf
rcases Nat.eq_zero_or_pos n with h | h
· subst h
simp
· rw [div_le_one (by exact_mod_cast h)]
exact_mod_cast le_trans (Finset.card_le_card (Finset.filter_subset _ _)) (by simp)
/-- **The fraction is nondecreasing in the value.** -/
theorem cdf_mono (x : Fin n → ℝ) {s t : ℝ} (h : s ≤ t) : cdf x s ≤ cdf x t := by
unfold cdf
apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg n)
apply Nat.cast_le.mpr
apply Finset.card_le_card
intro i hi
rw [Finset.mem_filter] at hi ⊢
exact ⟨hi.1, le_trans hi.2 h⟩
/-- **At or above every row the fraction is one.** -/
theorem cdf_of_all (x : Fin n → ℝ) (t : ℝ) (h : ∀ i, x i ≤ t) (hn : 0 < n) : cdf x t = 1 := by
unfold cdf
rw [Finset.filter_true_of_mem fun i _ => h i, Finset.card_univ, Fintype.card_fin,
div_self (Nat.cast_ne_zero.mpr hn.ne')]
/-- **Below every row the fraction is zero.** -/
theorem cdf_of_none (x : Fin n → ℝ) (t : ℝ) (h : ∀ i, t < x i) : cdf x t = 0 := by
unfold cdf
rw [Finset.filter_false_of_mem fun i _ => not_le.mpr (h i)]
simp
/-- **An upper percentile over a lower one is at least one.** -/
theorem ratio_ge_one (qlo qhi : ℝ) (h0 : 0 < qlo) (h : qlo ≤ qhi) : 1 ≤ qhi / qlo := by
rw [le_div_iff₀ h0, one_mul]
exact h
end DMO.Percentile