Jaccard.lean

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

/-
Jaccard.lean. Chapter 0 section 0.6 and chapter 3 section 3.1, the Jaccard coefficient.

The Jaccard coefficient of two sets is the size of their intersection over the size of
their union. It lies between zero and one, is one for a nonempty set against itself, is
symmetric, and is zero exactly when the sets are disjoint. It reads nothing outside the
union, which is the sense in which it discards joint absence.
-/
import Mathlib

namespace DMO.Jaccard

variable {α : Type*} [DecidableEq α]

/-- The Jaccard coefficient. -/
noncomputable def jaccard (A B : Finset α) : ℝ := ((A ∩ B).card : ℝ) / (A ∪ B).card

/-- **The coefficient is nonnegative.** -/
theorem jaccard_nonneg (A B : Finset α) : 0 ≤ jaccard A B := by
  unfold jaccard
  positivity

/-- **The coefficient is at most one.** -/
theorem jaccard_le_one (A B : Finset α) : jaccard A B ≤ 1 := by
  unfold jaccard
  rcases Nat.eq_zero_or_pos (A ∪ B).card with h | h
  · rw [h]
    simp
  · rw [div_le_one (by exact_mod_cast h)]
    exact_mod_cast Finset.card_le_card Finset.inter_subset_union

/-- **A nonempty set has coefficient one with itself.** -/
theorem jaccard_self (A : Finset α) (hA : A.Nonempty) : jaccard A A = 1 := by
  unfold jaccard
  rw [Finset.inter_self, Finset.union_self, div_self]
  exact_mod_cast hA.card_pos.ne'

/-- **The coefficient is symmetric.** -/
theorem jaccard_comm (A B : Finset α) : jaccard A B = jaccard B A := by
  unfold jaccard
  rw [Finset.inter_comm, Finset.union_comm]

/-- **The coefficient is zero exactly when the sets are disjoint.** -/
theorem jaccard_eq_zero_iff (A B : Finset α) (h : (A ∪ B).Nonempty) :
    jaccard A B = 0 ↔ Disjoint A B := by
  unfold jaccard
  rw [div_eq_zero_iff, Nat.cast_eq_zero, Nat.cast_eq_zero, Finset.card_eq_zero,
    Finset.card_eq_zero, Finset.disjoint_iff_inter_eq_empty]
  constructor
  · rintro (h1 | h1)
    · exact h1
    · exact absurd h1 h.ne_empty
  · intro h1
    exact Or.inl h1

/-- **A subset's coefficient is its share of the larger set.** -/
theorem jaccard_subset (A B : Finset α) (h : A ⊆ B) : jaccard A B = (A.card : ℝ) / B.card := by
  unfold jaccard
  rw [Finset.inter_eq_left.mpr h, Finset.union_eq_right.mpr h]

end DMO.Jaccard