Discretization.lean

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

/-
Discretization.lean. Chapter 2 section 2.5, discretization.

Discretization collapses an ordered quantity to a few labels by binning it at a fixed
width. The bin index is nondecreasing in the value, every value in a cell gets the cell's
index, two values in the same cell become indistinguishable, and a sample confined to `m`
cells has at most `m` distinct labels, which is the quotient the transform forms.
-/
import Mathlib

namespace DMO.Discretization

/-- The bin index at width `w`. -/
noncomputable def bin (w x : ℝ) : ℤ := ⌊x / w⌋

/-- **The bin index is nondecreasing in the value.** -/
theorem bin_mono (w : ℝ) (hw : 0 < w) {x y : ℝ} (h : x ≤ y) : bin w x ≤ bin w y :=
  Int.floor_mono (div_le_div_of_nonneg_right h hw.le)

/-- **Every value in the `k`-th cell gets index `k`.** -/
theorem bin_of_mem (w : ℝ) (hw : 0 < w) (x : ℝ) (k : ℤ) (hx : k * w ≤ x ∧ x < ((k : ℝ) + 1) * w) :
    bin w x = k := by
  unfold bin
  rw [Int.floor_eq_iff]
  constructor
  · rw [le_div_iff₀ hw]
    exact hx.1
  · rw [div_lt_iff₀ hw]
    exact hx.2

/-- **Two values in the same cell become indistinguishable.** -/
theorem bin_eq_of_same_cell (w : ℝ) (hw : 0 < w) (x y : ℝ) (k : ℤ)
    (hx : k * w ≤ x ∧ x < ((k : ℝ) + 1) * w) (hy : k * w ≤ y ∧ y < ((k : ℝ) + 1) * w) :
    bin w x = bin w y := by
  rw [bin_of_mem w hw x k hx, bin_of_mem w hw y k hy]

/-- **A sample confined to `m` cells has at most `m` distinct labels.** -/
theorem card_bins_le (w : ℝ) (hw : 0 < w) (m : ℕ) (s : Finset ℝ)
    (hs : ∀ x ∈ s, 0 ≤ x ∧ x < m * w) : (s.image (bin w)).card ≤ m := by
  calc (s.image (bin w)).card ≤ (Finset.Ico (0 : ℤ) m).card := by
        apply Finset.card_le_card
        intro k hk
        rw [Finset.mem_image] at hk
        obtain ⟨x, hx, rfl⟩ := hk
        rw [Finset.mem_Ico]
        constructor
        · exact Int.floor_nonneg.mpr (div_nonneg (hs x hx).1 hw.le)
        · rw [bin, Int.floor_lt]
          push_cast
          rw [div_lt_iff₀ hw]
          exact (hs x hx).2
    _ = m := by simp

end DMO.Discretization