lean/FeedbackChannel/PatchDP.lean

View on GitHub

  1import Mathlib.Tactic
  2import Mathlib.Data.Finset.Lattice.Fold
  3import Mathlib.Algebra.BigOperators.Group.Multiset.Basic
  4
  5/-!
  6# The adaptive patch programme (lattice note §3)
  7
  8Source: `paper/evaluation_feedback_lattice.md` (version 0.6), §3, and the dynamic programme
  9`_optimal_value` of `src/spiral_ln/evaluation_feedback_lattice.py`.
 10
 11**Model.** The loop sees, per category, the pair `(n, F)`: `n` unpatched items, `F` of which still
 12fail. A *state* is the multiset of these pairs (categories with equal pairs are exchangeable, which
 13is the Python state, a sorted tuple of pairs). A patch picks a category with `n ≥ 1` and a uniformly
 14random unpatched item in it: it hits with probability `F / n`, leaving `(n - 1, F - 1)`, and
 15otherwise leaves `(n - 1, F)`. The run stops when `H` hits have been made. `val H s` is the minimum
 16expected number of patches, defined by the Bellman recursion (`dp`, fuel = items left; every patch
 17consumes one item, so the fuel is exact).
 18
 19Differences from the Python programme, none of which changes a value on a feasible state:
 20* the Python state drops categories with `F = 0`; here they stay and *may be chosen* (a wasted
 21  patch), as the note's policy class allows ("a category they choose"). The theorems below show
 22  such patches are never better.
 23* on an infeasible state (`H` larger than the failures left, in particular no item left) the value
 24  is a junk `0`; every theorem assumes feasibility.
 25-/
 26
 27namespace FeedbackChannel.PatchDP
 28
 29/-- A category as the loop sees it: `(n, F)`, unpatched items and failures among them. -/
 30abbrev Cat := ℕ × ℕ
 31
 32/-- Hit probability of a patch in `c`: `F / n`. -/
 33def rate (c : Cat) : ℚ := (c.2 : ℚ) / c.1
 34
 35/-- The category after a hit. -/
 36def hitC (c : Cat) : Cat := (c.1 - 1, c.2 - 1)
 37
 38/-- The category after a miss. -/
 39def missC (c : Cat) : Cat := (c.1 - 1, c.2)
 40
 41/-- Unpatched items left in a state. -/
 42def items (s : Multiset Cat) : ℕ := (s.map Prod.fst).sum
 43
 44/-- Failures left in a state. -/
 45def fails (s : Multiset Cat) : ℕ := (s.map Prod.snd).sum
 46
 47/-- A state is valid when every category has `F ≤ n`. -/
 48def Valid (s : Multiset Cat) : Prop := ∀ c ∈ s, c.2 ≤ c.1
 49
 50instance : DecidablePred Valid := fun s => by unfold Valid; infer_instance
 51
 52/-- The categories a patch may go to: those with an unpatched item. -/
 53def choices (s : Multiset Cat) : Finset Cat := s.toFinset.filter (fun c => 0 < c.1)
 54
 55/-- The Bellman recursion with fuel. `dp k H s`: minimum expected patches to `H` more hits. -/
 56def dp : ℕ → ℕ → Multiset Cat → ℚ
 57  | 0, _, _ => 0
 58  | _ + 1, 0, _ => 0
 59  | k + 1, H + 1, s =>
 60    if h : (choices s).Nonempty then
 61      (choices s).inf' h fun c =>
 62        1 + rate c * dp k H (hitC c ::ₘ s.erase c) + (1 - rate c) * dp k (H + 1) (missC c ::ₘ s.erase c)
 63    else 0
 64
 65/-- The optimal expected number of patches to `H` hits from state `s` (`V*` of the note). -/
 66def val (H : ℕ) (s : Multiset Cat) : ℚ := dp (items s) H s
 67
 68/-- Expected patches to `H ≥ 1` hits when the first patch goes to `c` and every later patch is
 69optimal (`first_patch_values` / `_continuation` in the Python module). -/
 70def firstPatch (H : ℕ) (s : Multiset Cat) (c : Cat) : ℚ :=
 71  1 + rate c * val (H - 1) (hitC c ::ₘ s.erase c) + (1 - rate c) * val H (missC c ::ₘ s.erase c)
 72
 73/-- The one-hit value of a category, `(n + 1) / (F + 1)`: the note's "finisher". -/
 74def finisher (c : Cat) : ℚ := ((c.1 : ℚ) + 1) / ((c.2 : ℚ) + 1)
 75
 76/-! ### Bookkeeping -/
 77
 78@[simp] lemma rate_mk (n F : ℕ) : rate (n, F) = (F : ℚ) / n := rfl
 79@[simp] lemma finisher_mk (n F : ℕ) : finisher (n, F) = ((n : ℚ) + 1) / ((F : ℚ) + 1) := rfl
 80@[simp] lemma hitC_mk (n F : ℕ) : hitC (n, F) = (n - 1, F - 1) := rfl
 81@[simp] lemma missC_mk (n F : ℕ) : missC (n, F) = (n - 1, F) := rfl
 82
 83lemma items_cons (x : Cat) (s : Multiset Cat) : items (x ::ₘ s) = x.1 + items s := by
 84  simp [items]
 85
 86lemma items_erase {s : Multiset Cat} {c : Cat} (hc : c ∈ s) : items s = c.1 + items (s.erase c) := by
 87  conv_lhs => rw [← Multiset.cons_erase hc]
 88  exact items_cons _ _
 89
 90lemma fst_le_items {s : Multiset Cat} {c : Cat} (hc : c ∈ s) : c.1 ≤ items s := by
 91  rw [items_erase hc]; omega
 92
 93lemma items_after {s : Multiset Cat} {c : Cat} (hc : c ∈ s) (hpos : 0 < c.1) (m : ℕ) :
 94    items ((c.1 - 1, m) ::ₘ s.erase c) + 1 = items s := by
 95  rw [items_cons, items_erase hc]; simp only; omega
 96
 97lemma mem_after {s : Multiset Cat} {c x d : Cat} (hd : d ∈ x ::ₘ s.erase c) : d = x ∨ d ∈ s := by
 98  rcases Multiset.mem_cons.1 hd with h | h
 99  · exact Or.inl h
100  · exact Or.inr (Multiset.mem_of_mem_erase h)
101
102lemma mem_choices {s : Multiset Cat} {c : Cat} : c ∈ choices s ↔ c ∈ s ∧ 0 < c.1 := by
103  simp [choices]
104
105lemma dp_zero_hits (k : ℕ) (s : Multiset Cat) : dp k 0 s = 0 := by
106  cases k <;> simp [dp]
107
108@[simp] lemma val_zero (s : Multiset Cat) : val 0 s = 0 := dp_zero_hits _ _
109
110/-- **Bellman equation.** With at least one hit needed and a patchable category, the optimum is
111the minimum over the first patch of its continuation value. -/
112theorem val_succ (H : ℕ) (s : Multiset Cat) (h : (choices s).Nonempty) :
113    val (H + 1) s = (choices s).inf' h (firstPatch (H + 1) s) := by
114  obtain ⟨c0, hc0⟩ := id h
115  rw [mem_choices] at hc0
116  obtain ⟨k, hk⟩ : ∃ k, items s = k + 1 := ⟨items s - 1, by have := fst_le_items hc0.1; omega⟩
117  unfold val
118  rw [hk, dp, dif_pos h]
119  refine Finset.inf'_congr h rfl (fun c hc => ?_)
120  rw [mem_choices] at hc
121  have e1 : items (hitC c ::ₘ s.erase c) = k := by
122    have := items_after hc.1 hc.2 (c.2 - 1); simp only [hitC]; omega
123  have e2 : items (missC c ::ₘ s.erase c) = k := by
124    have := items_after hc.1 hc.2 c.2; simp only [missC]; omega
125  simp only [firstPatch, val, e1, e2, Nat.add_sub_cancel]
126
127lemma val_le_firstPatch (H : ℕ) (s : Multiset Cat) (c : Cat) (hc : c ∈ s) (hpos : 0 < c.1) :
128    val (H + 1) s ≤ firstPatch (H + 1) s c := by
129  have h : (choices s).Nonempty := ⟨c, mem_choices.2 ⟨hc, hpos⟩⟩
130  rw [val_succ H s h]
131  exact Finset.inf'_le _ (mem_choices.2 ⟨hc, hpos⟩)
132
133lemma le_val_of_forall (H : ℕ) (s : Multiset Cat) (h : (choices s).Nonempty) (x : ℚ)
134    (hx : ∀ c ∈ s, 0 < c.1 → x ≤ firstPatch (H + 1) s c) : x ≤ val (H + 1) s := by
135  rw [val_succ H s h]
136  exact Finset.le_inf' _ _ fun c hc => hx c (mem_choices.1 hc).1 (mem_choices.1 hc).2
137
138/-- Certificate form of the Bellman equation, used for exact evaluation on concrete states. -/
139theorem val_eq_of_cert (H : ℕ) (s : Multiset Cat) (q : ℚ) (c : Cat) (hc : c ∈ s) (hpos : 0 < c.1)
140    (heq : firstPatch (H + 1) s c = q) (hle : ∀ d ∈ s, 0 < d.1 → q ≤ firstPatch (H + 1) s d) :
141    val (H + 1) s = q :=
142  le_antisymm (heq ▸ val_le_firstPatch H s c hc hpos)
143    (le_val_of_forall H s ⟨c, mem_choices.2 ⟨hc, hpos⟩⟩ q hle)
144
145lemma rate_nonneg (c : Cat) : 0 ≤ rate c := by
146  unfold rate; positivity
147
148lemma rate_le_one {c : Cat} (h : c.2 ≤ c.1) : rate c ≤ 1 := by
149  unfold rate
150  rcases Nat.eq_zero_or_pos c.1 with h0 | h0
151  · simp [h0]
152  · rw [div_le_one (by exact_mod_cast h0)]; exact_mod_cast h
153
154lemma rate_eq_one {c : Cat} (h : c.2 = c.1) (hpos : 0 < c.1) : rate c = 1 := by
155  unfold rate; rw [h]; exact div_self (by exact_mod_cast hpos.ne')
156
157lemma valid_after_hit {s : Multiset Cat} {c : Cat} (hv : Valid s) (hc : c ∈ s) :
158    Valid (hitC c ::ₘ s.erase c) := by
159  intro d hd
160  rcases mem_after hd with rfl | h
161  · have := hv c hc; simp only [hitC]; omega
162  · exact hv d h
163
164lemma valid_after_miss {s : Multiset Cat} {c : Cat} (hv : Valid s) (hlt : c.2 < c.1) :
165    Valid (missC c ::ₘ s.erase c) := by
166  intro d hd
167  rcases mem_after hd with rfl | h
168  · simp only [missC]; omega
169  · exact hv d h
170
171/-! ### Theorem 10: one hit -/
172
173/-- Arithmetic of the induction step (the note's two branches). -/
174lemma one_hit_step (n F x : ℚ) (hn : 0 < n) (hF : 1 ≤ F) (hFn : F < n)
175    (hx : x ≤ (n + 1) / (F + 1)) : x ≤ 1 + (1 - F / n) * min x (n / (F + 1)) := by
176  have hF1 : 0 < F + 1 := by linarith
177  rcases le_total x (n / (F + 1)) with h | h
178  · rw [min_eq_left h]
179    -- `(F / n) x ≤ (F / n) (n / (F + 1)) = F / (F + 1) ≤ 1`
180    have hp : 0 ≤ F / n := by positivity
181    have h1 : F / n * x ≤ F / n * (n / (F + 1)) := mul_le_mul_of_nonneg_left h hp
182    have h2 : F / n * (n / (F + 1)) = F / (F + 1) := by field_simp
183    have h3 : F / (F + 1) ≤ 1 := by rw [div_le_one hF1]; linarith
184    nlinarith
185  · rw [min_eq_right h]
186    have : 1 + (1 - F / n) * (n / (F + 1)) = (n + 1) / (F + 1) := by
187      field_simp; ring
188    linarith
189
190/-- Upper half of Theorem 10: patching any failing category until it hits costs its finisher
191value, so the optimum is at most every finisher. -/
192theorem val_one_le_finisher : ∀ (k : ℕ) (s : Multiset Cat), items s = k → Valid s →
193    ∀ c ∈ s, 1 ≤ c.2 → val 1 s ≤ finisher c := by
194  intro k
195  induction k with
196  | zero =>
197    intro s hk hv c hc hF
198    have := fst_le_items hc; have := hv c hc; omega
199  | succ k ih =>
200    intro s hk hv c hc hF
201    have hcn := hv c hc
202    have hpos : 0 < c.1 := by omega
203    refine (val_le_firstPatch 0 s c hc hpos).trans ?_
204    obtain ⟨n, F⟩ := c
205    simp only at hF hcn hpos
206    unfold firstPatch
207    simp only [zero_add, Nat.sub_self, val_zero, mul_zero, add_zero, rate_mk, finisher_mk]
208    rcases Nat.lt_or_ge F n with hlt | hge
209    · -- a miss leaves `(n - 1, F)` with `F ≥ 1`; its finisher is `n / (F + 1)`
210      have hv' := valid_after_miss (c := (n, F)) hv hlt
211      have hk' : items (missC (n, F) ::ₘ s.erase (n, F)) = k := by
212        have := items_after hc hpos F; dsimp only at this; simp only [missC_mk]; omega
213      have hih := ih _ hk' hv' (missC (n, F)) (Multiset.mem_cons_self _ _)
214        (by simp only [missC_mk]; omega)
215      have hfin : finisher (missC (n, F)) = (n : ℚ) / ((F : ℚ) + 1) := by
216        simp only [missC_mk, finisher_mk]
217        rw [Nat.cast_sub (by omega)]; push_cast; ring
218      rw [hfin] at hih
219      have hq : (0 : ℚ) ≤ 1 - (F : ℚ) / n := by
220        have := rate_le_one (c := (n, F)) (by simpa using hcn); simp at this; linarith
221      have hnq : (0 : ℚ) < n := by exact_mod_cast hpos
222      calc 1 + (1 - (F : ℚ) / n) * val 1 (missC (n, F) ::ₘ s.erase (n, F))
223          ≤ 1 + (1 - (F : ℚ) / n) * ((n : ℚ) / ((F : ℚ) + 1)) := by gcongr
224        _ = ((n : ℚ) + 1) / ((F : ℚ) + 1) := by field_simp; ring
225    · have hFn : F = n := le_antisymm hcn hge
226      subst hFn
227      have hnq : (F : ℚ) ≠ 0 := by exact_mod_cast hpos.ne'
228      rw [div_self hnq, div_self (by positivity)]
229      ring_nf; rfl
230
231/-- Lower half of Theorem 10, the note's induction: any `x` below every finisher is below the
232optimum. -/
233theorem le_val_one : ∀ (k : ℕ) (s : Multiset Cat), items s = k → Valid s → (∃ c ∈ s, 1 ≤ c.2) →
234    ∀ x : ℚ, (∀ c ∈ s, 1 ≤ c.2 → x ≤ finisher c) → x ≤ val 1 s := by
235  intro k
236  induction k with
237  | zero =>
238    intro s hk hv ⟨c, hc, hF⟩
239    have := fst_le_items hc; have := hv c hc; omega
240  | succ k ih =>
241    intro s hk hv ⟨c0, hc0, hF0⟩ x hx
242    have hpos0 : 0 < c0.1 := by have := hv c0 hc0; omega
243    refine le_val_of_forall 0 s ⟨c0, mem_choices.2 ⟨hc0, hpos0⟩⟩ x ?_
244    intro c hc hpos
245    have hcn := hv c hc
246    have hk' : items (missC c ::ₘ s.erase c) = k := by
247      have := items_after hc hpos c.2; unfold missC; omega
248    unfold firstPatch
249    simp only [zero_add, Nat.sub_self, val_zero, mul_zero, add_zero]
250    rcases Nat.lt_or_ge c.2 c.1 with hlt | hge
251    · have hv' := valid_after_miss hv hlt
252      have hq : (0 : ℚ) ≤ 1 - rate c := by have := rate_le_one hcn; linarith
253      rcases Nat.eq_zero_or_pos c.2 with h0 | h1
254      · -- a category with no failure: the miss changes nothing that matters
255        have hex : ∃ d ∈ missC c ::ₘ s.erase c, 1 ≤ d.2 := by
256          refine ⟨c0, Multiset.mem_cons_of_mem ?_, hF0⟩
257          exact (Multiset.mem_erase_of_ne (by rintro rfl; omega)).2 hc0
258        have hx' : ∀ d ∈ missC c ::ₘ s.erase c, 1 ≤ d.2 → x ≤ finisher d := by
259          intro d hd hdF
260          rcases mem_after hd with rfl | h
261          · simp only [missC] at hdF; omega
262          · exact hx d h hdF
263        have := ih _ hk' hv' hex x hx'
264        have hr : rate c = 0 := by simp [rate, h0]
265        rw [hr]; linarith
266      · -- the note's case: `y = min x (n / (F + 1))` is below every finisher after the miss
267        obtain ⟨n, F⟩ := c
268        simp only at hlt h1 hpos hcn
269        set y := min x ((n : ℚ) / ((F : ℚ) + 1)) with hy
270        have hex : ∃ d ∈ missC (n, F) ::ₘ s.erase (n, F), 1 ≤ d.2 :=
271          ⟨missC (n, F), Multiset.mem_cons_self _ _, by simp only [missC_mk]; omega⟩
272        have hy' : ∀ d ∈ missC (n, F) ::ₘ s.erase (n, F), 1 ≤ d.2 → y ≤ finisher d := by
273          intro d hd hdF
274          rcases mem_after hd with rfl | h
275          · simp only [missC_mk, finisher_mk]
276            rw [Nat.cast_sub (by omega)]; push_cast
277            simp only [sub_add_cancel]
278            exact min_le_right _ _
279          · exact (min_le_left _ _).trans (hx d h hdF)
280        have hih := ih _ hk' hv' hex y hy'
281        have hstep := one_hit_step n F x (by exact_mod_cast hpos) (by exact_mod_cast h1)
282          (by exact_mod_cast hlt) (by simpa using hx (n, F) hc h1)
283        rw [← hy] at hstep
284        simp only [rate_mk] at hq ⊢
285        calc x ≤ 1 + (1 - (F : ℚ) / n) * y := hstep
286          _ ≤ 1 + (1 - (F : ℚ) / n) * val 1 (missC (n, F) ::ₘ s.erase (n, F)) := by gcongr
287    · -- `F = n`: the patch hits for sure, cost `1 = (n + 1) / (n + 1)`
288      have hFn : c.2 = c.1 := le_antisymm hcn hge
289      have hr := rate_eq_one hFn hpos
290      rw [hr]
291      have := hx c hc (by omega)
292      simp only [finisher, hFn] at this
293      rw [div_self (by positivity)] at this
294      linarith
295
296/-- **Theorem 10 (one hit, closed form).** For a valid state with at least one failing category,
297the optimal expected number of patches to one hit is the least `(n_c + 1) / (F_c + 1)` over the
298categories with `F_c ≥ 1`. -/
299theorem theorem10 (s : Multiset Cat) (hv : Valid s) (hF : ∃ c ∈ s, 1 ≤ c.2) :
300    IsLeast {x | ∃ c ∈ s, 1 ≤ c.2 ∧ x = finisher c} (val 1 s) := by
301  set T := s.toFinset.filter (fun c => 1 ≤ c.2) with hT
302  have hTne : T.Nonempty := by
303    obtain ⟨c, hc, hc1⟩ := hF; exact ⟨c, by simp [hT, hc, hc1]⟩
304  obtain ⟨c, hcT, hceq⟩ := Finset.exists_mem_eq_inf' hTne finisher
305  have hcs : c ∈ s ∧ 1 ≤ c.2 := by simpa [hT] using hcT
306  have hmin : ∀ d ∈ s, 1 ≤ d.2 → finisher c ≤ finisher d := by
307    intro d hd hd1
308    rw [← hceq]; exact Finset.inf'_le _ (by simp [hT, hd, hd1])
309  refine ⟨⟨c, hcs.1, hcs.2, ?_⟩, ?_⟩
310  · exact le_antisymm (val_one_le_finisher _ s rfl hv c hcs.1 hcs.2)
311      (le_val_one _ s rfl hv hF _ hmin)
312  · rintro x ⟨d, hd, hd1, rfl⟩
313    exact val_one_le_finisher _ s rfl hv d hd hd1
314
315/-- Theorem 10 in evaluation form: a category of least finisher value gives the optimum. -/
316theorem val_one_eq (s : Multiset Cat) (hv : Valid s) (c : Cat) (hc : c ∈ s) (hc1 : 1 ≤ c.2)
317    (hmin : ∀ d ∈ s, 1 ≤ d.2 → finisher c ≤ finisher d) : val 1 s = finisher c :=
318  le_antisymm (val_one_le_finisher _ s rfl hv c hc hc1) (le_val_one _ s rfl hv ⟨c, hc, hc1⟩ _ hmin)
319
320/-- Expected patches when the loop patches category `(n, F)` until it hits and never switches:
321`stick (n + 1) F = 1 + (1 - F / (n + 1)) * stick n F` (a miss leaves `n` items, `F` failures). -/
322def stick : ℕ → ℕ → ℚ
323  | 0, _ => 0
324  | n + 1, F => 1 + (1 - (F : ℚ) / (n + 1)) * stick n F
325
326/-- Sticking with a category costs its finisher value (the note's identity
327`1 + (1 - F/n) n/(F+1) = (n+1)/(F+1)`, iterated). -/
328theorem stick_eq : ∀ (n F : ℕ), 1 ≤ F → F ≤ n → stick n F = ((n : ℚ) + 1) / ((F : ℚ) + 1) := by
329  intro n
330  induction n with
331  | zero => intro F h1 h2; omega
332  | succ n ih =>
333    intro F h1 h2
334    simp only [stick]
335    rcases Nat.lt_or_ge F (n + 1) with hlt | hge
336    · rw [ih F h1 (by omega)]
337      push_cast
338      field_simp
339      ring
340    · have hF : F = n + 1 := le_antisymm h2 hge
341      subst hF
342      push_cast
343      rw [div_self (by positivity)]
344      simp only [sub_self, zero_mul, add_zero]
345      rw [div_self (by positivity)]
346
347/-- **Theorem 10, attainment.** Let `c` be a best finisher of a valid state. Then (i) patching `c`
348first is optimal; (ii) after a miss in `c` the remaining `(n - 1, F)` is a best finisher of the new
349state, so continuing with it is again optimal (the policy never switches); (iii) the never-switching
350policy costs `stick n F = (n + 1) / (F + 1)`, the optimum. -/
351theorem theorem10_attained (s : Multiset Cat) (hv : Valid s) (c : Cat) (hc : c ∈ s) (hc1 : 1 ≤ c.2)
352    (hbest : finisher c = val 1 s) :
353    firstPatch 1 s c = val 1 s ∧
354    (c.2 < c.1 → finisher (missC c) = val 1 (missC c ::ₘ s.erase c)) ∧
355    stick c.1 c.2 = val 1 s := by
356  have hcn := hv c hc
357  have hpos : 0 < c.1 := by omega
358  have hmin : ∀ d ∈ s, 1 ≤ d.2 → finisher c ≤ finisher d := by
359    intro d hd hd1; rw [hbest]; exact val_one_le_finisher _ s rfl hv d hd hd1
360  -- after a miss, `missC c` is a best finisher
361  have hmiss : c.2 < c.1 → finisher (missC c) = val 1 (missC c ::ₘ s.erase c) := by
362    intro hlt
363    have hv' := valid_after_miss hv hlt
364    have hlt' : finisher (missC c) < finisher c := by
365      obtain ⟨n, F⟩ := c
366      simp only at hlt hpos
367      simp only [missC_mk, finisher_mk]
368      rw [Nat.cast_sub (by omega)]; push_cast
369      apply div_lt_div_of_pos_right _ (by positivity); linarith
370    symm
371    apply val_one_eq _ hv' _ (Multiset.mem_cons_self _ _) (by simpa [missC] using hc1)
372    intro d hd hd1
373    rcases mem_after hd with rfl | h
374    · exact le_rfl
375    · exact hlt'.le.trans (hmin d h hd1)
376  refine ⟨?_, hmiss, ?_⟩
377  · apply le_antisymm _ (val_le_firstPatch 0 s c hc hpos)
378    unfold firstPatch
379    simp only [zero_add, Nat.sub_self, val_zero, mul_zero, add_zero]
380    rcases Nat.lt_or_ge c.2 c.1 with hlt | hge
381    · rw [← hmiss hlt, ← hbest]
382      obtain ⟨n, F⟩ := c
383      simp only at hlt hpos hc1
384      simp only [missC_mk, finisher_mk, rate_mk]
385      rw [Nat.cast_sub (by omega)]; push_cast
386      have : (n : ℚ) ≠ 0 := by exact_mod_cast hpos.ne'
387      apply le_of_eq
388      field_simp
389      ring
390    · have hFn : c.2 = c.1 := le_antisymm hcn hge
391      rw [rate_eq_one hFn hpos, ← hbest]
392      simp only [finisher, hFn]
393      rw [div_self (by positivity)]
394      ring_nf; rfl
395  · rw [stick_eq _ _ hc1 hcn, ← hbest]; rfl
396
397/-- The one-hit witness of the note: in `{(2,1), (16,9)}` the rates are `1/2 < 9/16` but patching
398`(2,1)` first costs `3/2`, the optimum, and patching the higher-rate `(16,9)` first costs `53/32`. -/
399theorem one_hit_rate_witness :
400    rate (2, 1) < rate (16, 9) ∧
401    val 1 {(2, 1), (16, 9)} = 3 / 2 ∧
402    firstPatch 1 {(2, 1), (16, 9)} (2, 1) = 3 / 2 ∧
403    firstPatch 1 {(2, 1), (16, 9)} (16, 9) = 53 / 32 := by
404  have hv : Valid {(2, 1), (16, 9)} := by decide
405  have h0 : val 1 {(2, 1), (16, 9)} = 3 / 2 := by
406    rw [val_one_eq _ hv (2, 1) (by decide) (by decide)]
407    · norm_num
408    · intro d hd _
409      simp only [Multiset.insert_eq_cons, Multiset.mem_cons, Multiset.mem_singleton] at hd
410      rcases hd with rfl | rfl <;> norm_num
411  have e1 : missC (16, 9) ::ₘ ({(2, 1), (16, 9)} : Multiset Cat).erase (16, 9) = {(15, 9), (2, 1)} := by
412    decide
413  have hv1 : Valid {(15, 9), (2, 1)} := by decide
414  have h1 : val 1 {(15, 9), (2, 1)} = 3 / 2 := by
415    rw [val_one_eq _ hv1 (2, 1) (by decide) (by decide)]
416    · norm_num
417    · intro d hd _
418      simp only [Multiset.insert_eq_cons, Multiset.mem_cons, Multiset.mem_singleton] at hd
419      rcases hd with rfl | rfl <;> norm_num
420  have e2 : missC (2, 1) ::ₘ ({(2, 1), (16, 9)} : Multiset Cat).erase (2, 1) = {(1, 1), (16, 9)} := by
421    decide
422  have hv2 : Valid {(1, 1), (16, 9)} := by decide
423  have h2 : val 1 {(1, 1), (16, 9)} = 1 := by
424    rw [val_one_eq _ hv2 (1, 1) (by decide) (by decide)]
425    · norm_num
426    · intro d hd _
427      simp only [Multiset.insert_eq_cons, Multiset.mem_cons, Multiset.mem_singleton] at hd
428      rcases hd with rfl | rfl <;> norm_num
429  refine ⟨by norm_num, h0, ?_, ?_⟩
430  · rw [firstPatch, e2, h2]; norm_num
431  · rw [firstPatch, e1, h1]; norm_num
432
433/-! ### Proposition 4, one category: the negative-hypergeometric mean -/
434
435/-- **Proposition 4, one category.** With a single category of `n` items, `F` of them failing, the
436expected number of patches to the `H`-th hit (`H ≤ F`) is `H (n + 1) / (F + 1)`. With one category
437the programme has one choice per step, so `val` is the expected stopping time of patching uniformly
438at random without replacement. -/
439theorem val_single : ∀ (n H F : ℕ), H ≤ F → F ≤ n →
440    val H {(n, F)} = (H : ℚ) * ((n : ℚ) + 1) / ((F : ℚ) + 1) := by
441  intro n
442  induction n with
443  | zero =>
444    intro H F h1 h2
445    have hF : F = 0 := by omega
446    have hH : H = 0 := by omega
447    subst hF; subst hH; simp
448  | succ n ih =>
449    intro H F h1 h2
450    rcases H with _ | h
451    · simp
452    obtain ⟨G, rfl⟩ : ∃ G, F = G + 1 := ⟨F - 1, by omega⟩
453    have hs : ({(n + 1, G + 1)} : Multiset Cat).erase (n + 1, G + 1) = 0 :=
454      Multiset.erase_singleton _
455    have hfp : firstPatch (h + 1) {(n + 1, G + 1)} (n + 1, G + 1) =
456        ((h + 1 : ℕ) : ℚ) * (((n + 1 : ℕ) : ℚ) + 1) / (((G + 1 : ℕ) : ℚ) + 1) := by
457      unfold firstPatch
458      rw [hs, Multiset.cons_zero, Multiset.cons_zero]
459      simp only [hitC_mk, missC_mk, rate_mk, Nat.add_sub_cancel]
460      rw [ih h G (by omega) (by omega)]
461      rcases Nat.lt_or_ge G n with hlt | hge
462      · rw [ih (h + 1) (G + 1) (by omega) (by omega)]
463        push_cast
464        field_simp
465        ring
466      · have hG : G = n := by omega
467        subst hG
468        push_cast
469        rw [div_self (by positivity)]
470        field_simp
471        ring
472    exact val_eq_of_cert h _ _ (n + 1, G + 1) (Multiset.mem_singleton_self _) (by simp) hfp
473      (fun d hd _ => by rw [Multiset.mem_singleton.1 hd, hfp])
474
475/-! ### Lemma 9: pair commutation -/
476
477/-- Expected patches when the first patch goes to `A`, the second to `B`, and every later patch is
478optimal (`two_patch_value` in the Python module). Meant for `H ≥ 2`, so the run cannot stop before
479the second patch. -/
480def twoPatch (H : ℕ) (s : Multiset Cat) (A B : Cat) : ℚ :=
481  rate A * (1 + firstPatch (H - 1) (hitC A ::ₘ s.erase A) B) +
482    (1 - rate A) * (1 + firstPatch H (missC A ::ₘ s.erase A) B)
483
484lemma erase_cons_of_mem {t : Multiset Cat} {B : Cat} (x : Cat) (hB : B ∈ t) :
485    (x ::ₘ t).erase B = x ::ₘ t.erase B := by
486  by_cases hx : x = B
487  · subst hx; rw [Multiset.erase_cons_head, Multiset.cons_erase hB]
488  · exact Multiset.erase_cons_tail_of_mem hB
489
490/-- **Lemma 9 (pair commutation).** With at least two hits needed, patching category `A` and then a
491different category `B`, each followed by optimal play, costs the same in expectation as `B` then
492`A`. -/
493theorem lemma9 (H : ℕ) (hH : 2 ≤ H) (s : Multiset Cat) (A B : Cat) (hA : A ∈ s) (hB : B ∈ s)
494    (hAB : A ≠ B) : twoPatch H s A B = twoPatch H s B A := by
495  have hB' : B ∈ s.erase A := (Multiset.mem_erase_of_ne hAB.symm).2 hB
496  have hA' : A ∈ s.erase B := (Multiset.mem_erase_of_ne hAB).2 hA
497  unfold twoPatch firstPatch
498  rw [erase_cons_of_mem (hitC A) hB', erase_cons_of_mem (missC A) hB',
499    erase_cons_of_mem (hitC B) hA', erase_cons_of_mem (missC B) hA']
500  have hc : (s.erase B).erase A = (s.erase A).erase B := Multiset.erase_comm _ _ _
501  rw [hc, Multiset.cons_swap (hitC A) (hitC B), Multiset.cons_swap (hitC A) (missC B),
502    Multiset.cons_swap (missC A) (hitC B), Multiset.cons_swap (missC A) (missC B)]
503  ring
504
505/-! ### Policies -/
506
507/-- A stationary policy: given the hits still needed and the state, the category it patches. -/
508abbrev Policy := ℕ → Multiset Cat → Cat
509
510/-- Expected patches of a policy (policy evaluation, same fuel convention as `dp`). -/
511def pdp (π : Policy) : ℕ → ℕ → Multiset Cat → ℚ
512  | 0, _, _ => 0
513  | _ + 1, 0, _ => 0
514  | k + 1, H + 1, s =>
515    1 + rate (π (H + 1) s) * pdp π k H (hitC (π (H + 1) s) ::ₘ s.erase (π (H + 1) s)) +
516      (1 - rate (π (H + 1) s)) * pdp π k (H + 1) (missC (π (H + 1) s) ::ₘ s.erase (π (H + 1) s))
517
518/-- Expected number of patches to `H` hits when following `π` from `s`. -/
519def pval (π : Policy) (H : ℕ) (s : Multiset Cat) : ℚ := pdp π (items s) H s
520
521/-- A policy is legal when, wherever a patch is possible, it patches a category of the state that
522has an unpatched item. -/
523def Legal (π : Policy) : Prop := ∀ H s, (choices s).Nonempty → π H s ∈ s ∧ 0 < (π H s).1
524
525lemma choices_nonempty_of_items {s : Multiset Cat} (h : 0 < items s) : (choices s).Nonempty := by
526  by_contra hne
527  have : items s = 0 := by
528    unfold items
529    apply Multiset.sum_eq_zero
530    intro x hx
531    obtain ⟨c, hc, rfl⟩ := Multiset.mem_map.1 hx
532    by_contra hc0
533    exact hne ⟨c, mem_choices.2 ⟨hc, Nat.pos_of_ne_zero hc0⟩⟩
534  omega
535
536lemma pval_succ (π : Policy) (hπ : Legal π) (H : ℕ) (s : Multiset Cat) (h : 0 < items s) :
537    pval π (H + 1) s = 1 + rate (π (H + 1) s) * pval π H (hitC (π (H + 1) s) ::ₘ s.erase (π (H + 1) s)) +
538      (1 - rate (π (H + 1) s)) * pval π (H + 1) (missC (π (H + 1) s) ::ₘ s.erase (π (H + 1) s)) := by
539  obtain ⟨hc, hpos⟩ := hπ (H + 1) s (choices_nonempty_of_items h)
540  obtain ⟨k, hk⟩ : ∃ k, items s = k + 1 := ⟨items s - 1, by omega⟩
541  have e1 : items (hitC (π (H + 1) s) ::ₘ s.erase (π (H + 1) s)) = k := by
542    have := items_after hc hpos ((π (H + 1) s).2 - 1); unfold hitC; omega
543  have e2 : items (missC (π (H + 1) s) ::ₘ s.erase (π (H + 1) s)) = k := by
544    have := items_after hc hpos (π (H + 1) s).2; unfold missC; omega
545  unfold pval
546  rw [hk, e1, e2]
547  rfl
548
549/-- No legal policy beats the programme, and following `π` costs at least the continuation value
550of its own first patch. -/
551theorem val_le_pval (π : Policy) (hπ : Legal π) : ∀ (k : ℕ) (H : ℕ) (s : Multiset Cat),
552    items s = k → Valid s → val H s ≤ pval π H s ∧
553      (0 < H → 0 < items s → firstPatch H s (π H s) ≤ pval π H s) := by
554  intro k
555  induction k with
556  | zero =>
557    intro H s hk _
558    refine ⟨?_, fun _ h => by omega⟩
559    unfold val pval; rw [hk]; simp [dp, pdp]
560  | succ k ih =>
561    intro H s hk hv
562    rcases H with _ | H
563    · refine ⟨?_, fun h => by omega⟩
564      simp only [val_zero]; unfold pval; rw [hk]; simp [pdp]
565    have hpos' : 0 < items s := by omega
566    obtain ⟨hc, hpos⟩ := hπ (H + 1) s (choices_nonempty_of_items hpos')
567    set c := π (H + 1) s with hcdef
568    have hfp : firstPatch (H + 1) s c ≤ pval π (H + 1) s := by
569      rw [pval_succ π hπ H s hpos', ← hcdef]
570      unfold firstPatch
571      simp only [Nat.add_sub_cancel]
572      have hk1 : items (hitC c ::ₘ s.erase c) = k := by
573        have := items_after hc hpos (c.2 - 1); unfold hitC; omega
574      have hk2 : items (missC c ::ₘ s.erase c) = k := by
575        have := items_after hc hpos c.2; unfold missC; omega
576      have h1 := (ih H _ hk1 (valid_after_hit hv hc)).1
577      have hr0 := rate_nonneg c
578      have hr1 := rate_le_one (hv c hc)
579      rcases Nat.lt_or_ge c.2 c.1 with hlt | hge
580      · have h2 := (ih (H + 1) _ hk2 (valid_after_miss hv hlt)).1
581        have hq : 0 ≤ 1 - rate c := by linarith
582        have := mul_le_mul_of_nonneg_left h1 hr0
583        have := mul_le_mul_of_nonneg_left h2 hq
584        linarith
585      · have hr : rate c = 1 := rate_eq_one (le_antisymm (hv c hc) hge) hpos
586        rw [hr]
587        have := h1
588        linarith
589    exact ⟨(val_le_firstPatch H s c hc hpos).trans hfp, fun _ _ => hfp⟩
590
591end FeedbackChannel.PatchDP