Shard.lean

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

/-
Shard.lean. Chapter 13 section 13.1, the shard.

A sharded index searches each partition separately and merges the results. If each shard
returns its own top `k` and the global top `k` is strict, the global top `k` lies inside
the union of the shards' answers, so a merge of the local answers loses nothing, and the
merge reads at most the number of shards times `k` candidates.
-/
import Mathlib

namespace DMO.Shard

open Finset

variable {ι : Type*} [DecidableEq ι]

/-- `T` is a top-`k` of the shard `P` under the score `s`: it has `k` members of `P` and
every member of `P` outside it scores no higher than any member. -/
def IsTop (s : ι → ℝ) (P T : Finset ι) (k : ℕ) : Prop :=
  T ⊆ P ∧ T.card = k ∧ ∀ y ∈ T, ∀ z ∈ P, z ∉ T → s z ≤ s y

/-- **The global top `k` lies inside each shard's top `k`.** With `S` a strict global
top set of at most `k` rows, every member of `S` in the shard is in the shard's answer. -/
theorem global_in_local (s : ι → ℝ) (P T S : Finset ι) (k : ℕ) (hT : IsTop s P T k)
    (hS : S.card ≤ k) (hstrict : ∀ y ∈ S, ∀ z, z ∉ S → s z < s y) : S ∩ P ⊆ T := by
  obtain ⟨_, hcard, hbest⟩ := hT
  intro x hx
  rw [Finset.mem_inter] at hx
  by_contra hxT
  have hTS : T ⊆ S := by
    intro y hy
    by_contra hyS
    have h1 := hstrict x hx.1 y hyS
    have h2 := hbest y hy x hx.2 hxT
    exact absurd h2 (not_le.mpr h1)
  have : (insert x T).card ≤ S.card := Finset.card_le_card (Finset.insert_subset hx.1 hTS)
  rw [Finset.card_insert_of_notMem hxT, hcard] at this
  omega

/-- **Merging the shards' answers loses nothing.** If the shards cover the global top set,
that set lies in the union of their answers. -/
theorem global_in_union {σ : Type*} (s : ι → ℝ) (J : Finset σ) (P T : σ → Finset ι)
    (S : Finset ι) (k : ℕ) (hT : ∀ j ∈ J, IsTop s (P j) (T j) k)
    (hcover : ∀ x ∈ S, ∃ j ∈ J, x ∈ P j) (hS : S.card ≤ k)
    (hstrict : ∀ y ∈ S, ∀ z, z ∉ S → s z < s y) : S ⊆ J.biUnion T := by
  intro x hx
  obtain ⟨j, hj, hxP⟩ := hcover x hx
  exact Finset.mem_biUnion.mpr
    ⟨j, hj, global_in_local s (P j) (T j) S k (hT j hj) hS hstrict (Finset.mem_inter.mpr ⟨hx, hxP⟩)⟩

/-- **The merge reads at most the number of shards times `k` candidates.** -/
theorem merge_cost {σ : Type*} [DecidableEq σ] (s : ι → ℝ) (J : Finset σ) (P T : σ → Finset ι)
    (k : ℕ) (hT : ∀ j ∈ J, IsTop s (P j) (T j) k) : (J.biUnion T).card ≤ J.card * k := by
  calc (J.biUnion T).card ≤ ∑ j ∈ J, (T j).card := Finset.card_biUnion_le
    _ = ∑ _j ∈ J, k := Finset.sum_congr rfl fun j hj => (hT j hj).2.1
    _ = J.card * k := by simp

end DMO.Shard