modulepublic import Research.PvsNP.Tau.TauConjecture@[expose] public sectionnamespace Research.PvsNP.Tau/-!# Canonicalization and Pruning Soundness for Constant-Free SLPsThis module formalizes the list-based straight-line program (`GateSpec`) representation,its equivalence with `SLP τ`, the canonicalization predicate `Canonical` used by theexhaustive enumerator, and the soundness theorems:1. `exists_canonical`: every nonzero polynomial `f` computed by a length-`t` `SLP`either belongs to `{1, -1, X, -X}` or is computed up to sign (`±f`) by a`Canonical` gate list of length `1 ≤ k ≤ t`.2. `deadgate_count_bound`: in any `Canonical` (or `UsedGates`) gate list of length `n`,after `d < n` gates, the number of unused gate wires `unusedWires gs d` satisfies`≤ n - d + 1`, and at the last gate (`d = n - 1`) at most `2` gate wires remain unusedand every unused gate wire must be an operand of the last gate.3. `zmax_le_of_checklist`, `zmax9_le_six_of_checklist`, `zmax10_le_seven_of_checklist`:conditional upper bounds transferring root-count bounds on all `Canonical` gate listsof length `1 ≤ n ≤ τ` to all nonzero `SLP t` with `t ≤ τ`.-//-! ## 1. List-Based Gate Representation & Equivalence with `SLP` -//-- A single gate in a list-based constant-free straight-line program.Gate `k` (0-based) reads wires `i` and `j` and outputs wire `k + 2`. -/structure GateSpec whereop : SLPOpi : ℕj : ℕderiving DecidableEq, Reprinstance : Inhabited GateSpec := ⟨⟨.add, 0, 0⟩⟩/-- Auxiliary accumulator evaluator for a list of gate specifications over `ℤ[X]`. -/noncomputable def wireValsAux : List (Polynomial ℤ) → List GateSpec → List (Polynomial ℤ)| acc, [] => acc| acc, g :: rest =>wireValsAux (acc ++ [g.op.applyPoly (acc.getD g.i 0) (acc.getD g.j 0)]) rest/-- Polynomial values of all wires `0, 1, ..., gs.length + 1` computed by `gs`.Wire `0` holds `1`, wire `1` holds `X`, and gate `k` computes wire `k + 2`. -/noncomputable def wireVals (gs : List GateSpec) : List (Polynomial ℤ) :=wireValsAux [1, Polynomial.X] gs/-- Output polynomial of `gs` (wire `gs.length + 1`, or `X` when `gs = []`). -/noncomputable def output (gs : List GateSpec) : Polynomial ℤ :=(wireVals gs).getD (gs.length + 1) 0/-- A gate list `gs` is well-formed when every gate `k` reads only wires `< k + 2`. -/def WellFormed (gs : List GateSpec) : Prop :=∀ (k : ℕ) (hk : k < gs.length), gs[k].i < k + 2 ∧ gs[k].j < k + 2private lemma getD_eq_getElem_of_lt {α : Type*} (l : List α) (d : α) {i : ℕ}(hi : i < l.length) : l.getD i d = l[i] := bysimp [List.getD, hi]private lemma getD_append_left {α : Type*} (l₁ l₂ : List α) (d : α) {i : ℕ}(hi : i < l₁.length) : (l₁ ++ l₂).getD i d = l₁.getD i d := byhave hi' : i < (l₁ ++ l₂).length := by simp; omegarw [getD_eq_getElem_of_lt _ d hi', getD_eq_getElem_of_lt _ d hi, List.getElem_append_left hi]private lemma getD_append_right {α : Type*} (l₁ l₂ : List α) (d : α) {i : ℕ}(hi : l₁.length ≤ i) : (l₁ ++ l₂).getD i d = l₂.getD (i - l₁.length) d := byby_cases hlt : i < (l₁ ++ l₂).length· have hlt2 : i - l₁.length < l₂.length := by simp at hlt; omegarw [getD_eq_getElem_of_lt _ d hlt, getD_eq_getElem_of_lt _ d hlt2, List.getElem_append_right hi]· have hge1 : (l₁ ++ l₂).length ≤ i := Nat.le_of_not_lt hlthave hge2 : l₂.length ≤ i - l₁.length := by simp at hge1; omegasimp [List.getD, List.getElem?_eq_none hge1, List.getElem?_eq_none hge2]theorem wireValsAux_length (acc : List (Polynomial ℤ)) (gs : List GateSpec) :(wireValsAux acc gs).length = acc.length + gs.length := byinduction gs generalizing acc with| nil => simp [wireValsAux]| cons g rest ih =>simp only [wireValsAux]rw [ih]simpomegatheorem wireVals_length (gs : List GateSpec) :(wireVals gs).length = gs.length + 2 := byrw [wireVals, wireValsAux_length]simpomegatheorem wireValsAux_append (acc : List (Polynomial ℤ)) (gs₁ gs₂ : List GateSpec) :wireValsAux acc (gs₁ ++ gs₂) = wireValsAux (wireValsAux acc gs₁) gs₂ := byinduction gs₁ generalizing acc with| nil => simp [wireValsAux]| cons g rest ih => simp [wireValsAux, ih]theorem wireVals_snoc (gs : List GateSpec) (g : GateSpec) :wireVals (gs ++ [g]) =wireVals gs ++ [g.op.applyPoly ((wireVals gs).getD g.i 0) ((wireVals gs).getD g.j 0)] := bysimp [wireVals, wireValsAux_append, wireValsAux]theorem wireValsAux_getD_lt (acc : List (Polynomial ℤ)) (gs : List GateSpec){w : ℕ} (hw : w < acc.length) :(wireValsAux acc gs).getD w 0 = acc.getD w 0 := byinduction gs generalizing acc with| nil => rfl| cons g rest ih =>have hw' : w < (acc ++ [g.op.applyPoly (acc.getD g.i 0) (acc.getD g.j 0)]).length := bysimp; omegarw [wireValsAux, ih _ hw', getD_append_left _ _ _ hw]theorem wireVals_zero (gs : List GateSpec) : (wireVals gs).getD 0 0 = 1 := byhave h := wireValsAux_getD_lt [1, Polynomial.X] gs (w := 0) (by decide)simpa [wireVals] using htheorem wireVals_one (gs : List GateSpec) : (wireVals gs).getD 1 0 = Polynomial.X := byhave h := wireValsAux_getD_lt [1, Polynomial.X] gs (w := 1) (by decide)simpa [wireVals] using htheorem wireVals_take_getD (gs : List GateSpec) {m w : ℕ}(hm : m ≤ gs.length) (hw : w < m + 2) :(wireVals (gs.take m)).getD w 0 = (wireVals gs).getD w 0 := byhave hsplit : gs = gs.take m ++ gs.drop m := (List.take_append_drop m gs).symmhave hlen : (wireVals (gs.take m)).length = m + 2 := byrw [wireVals_length, List.length_take, Nat.min_eq_left hm]have haux : wireVals gs = wireValsAux (wireVals (gs.take m)) (gs.drop m) := byrw [wireVals, wireVals, ← wireValsAux_append, ← hsplit]rw [haux]exact (wireValsAux_getD_lt (wireVals (gs.take m)) (gs.drop m) (hw.trans_eq hlen.symm)).symmtheorem wireVals_gate_take (gs : List GateSpec) {k : ℕ} (hk : k < gs.length) :(wireVals gs).getD (k + 2) 0 =(gs[k]).op.applyPoly((wireVals (gs.take k)).getD (gs[k]).i 0)((wireVals (gs.take k)).getD (gs[k]).j 0) := byhave htake : gs.take (k + 1) = gs.take k ++ [gs[k]] := List.take_add_one.trans (by simp [hk])have hlen : (wireVals (gs.take k)).length = k + 2 := byrw [wireVals_length, List.length_take, Nat.min_eq_left hk.le]have hw := wireVals_take_getD gs (m := k + 1) (w := k + 2) hk (by omega)rw [← hw, htake, wireVals_snoc, getD_append_right _ _ _ hlen.le]simp [hlen]theorem wireVals_gate (gs : List GateSpec) {k : ℕ} (hk : k < gs.length)(hi : gs[k].i < k + 2) (hj : gs[k].j < k + 2) :(wireVals gs).getD (k + 2) 0 =(gs[k]).op.applyPoly ((wireVals gs).getD gs[k].i 0) ((wireVals gs).getD gs[k].j 0) := byrw [wireVals_gate_take gs hk,wireVals_take_getD gs hk.le hi,wireVals_take_getD gs hk.le hj]theorem wireVals_gate_wf {gs : List GateSpec} (hwf : WellFormed gs) {k : ℕ} (hk : k < gs.length) :(wireVals gs).getD (k + 2) 0 =(gs[k]).op.applyPoly ((wireVals gs).getD gs[k].i 0) ((wireVals gs).getD gs[k].j 0) :=wireVals_gate gs hk (hwf k hk).1 (hwf k hk).2/-- Convert an `SLP τ` into a well-formed list of `τ` gate specifications. -/def SLP.toGateList : {τ : ℕ} → SLP τ → List GateSpec| 0, .nil => []| _ + 1, .snoc P op i j => P.toGateList ++ [⟨op, i.val, j.val⟩]theorem SLP.toGateList_length : ∀ {τ : ℕ} (P : SLP τ), P.toGateList.length = τ| 0, .nil => rfl| _ + 1, .snoc P _ _ _ => by simp [SLP.toGateList, P.toGateList_length]theorem SLP.toGateList_wellFormed : ∀ {τ : ℕ} (P : SLP τ), WellFormed P.toGateList| 0, .nil => fun k hk => by simp [SLP.toGateList] at hk| τ + 1, .snoc P op i j => byintro k hksimp only [SLP.toGateList, List.length_append, List.length_singleton, P.toGateList_length] at hkby_cases hlt : k < τ· have hlen : k < P.toGateList.length := by simpa [P.toGateList_length] using hltsimpa [SLP.toGateList, List.getElem_append_left hlen] using P.toGateList_wellFormed k hlen· have heq : k = τ := by omegasubst khave hlen : P.toGateList.length = τ := P.toGateList_lengthsimp only [SLP.toGateList, List.getElem_append_right hlen.le, hlen, Nat.sub_self,List.getElem_singleton]exact ⟨i.isLt, j.isLt⟩theorem SLP.wireVals_toGateList :∀ {τ : ℕ} (P : SLP τ) (k : Fin (τ + 2)),(wireVals P.toGateList).getD k.val 0 = P.evalWire k| 0, .nil, k => bysimp only [SLP.toGateList, wireVals, wireValsAux, SLP.evalWire]rcases k with ⟨kv, hkv⟩rcases kv with _ | _ | kv· simp [List.getD]· simp [List.getD]· omega| τ + 1, .snoc P op i j, k => bysimp only [SLP.toGateList, wireVals_snoc, SLP.evalWire]have hlen : (wireVals P.toGateList).length = τ + 2 := byrw [wireVals_length, P.toGateList_length]split_ifs with hk· rw [getD_append_left _ _ _ (hk.trans_eq hlen.symm)]exact P.wireVals_toGateList ⟨k.val, hk⟩· have hk_eq : k.val = τ + 2 := by omegarw [getD_append_right _ _ _ (by omega)]simp only [hlen, hk_eq, Nat.sub_self]rw [getD_eq_getElem_of_lt _ _ (by simp), List.getElem_singleton]rw [P.wireVals_toGateList i, P.wireVals_toGateList j]theorem SLP.output_toGateList {τ : ℕ} (P : SLP τ) :output P.toGateList = P.evalPoly := byhave h := P.wireVals_toGateList ⟨τ + 1, Nat.lt_succ_self _⟩simpa [output, SLP.evalPoly, P.toGateList_length] using h/-- Auxiliary builder turning the prefix of length `n ≤ gs.length` of a well-formed gate listinto an `SLP n`. -/def SLP.ofGateListAux (gs : List GateSpec) (hwf : WellFormed gs) :(n : ℕ) → n ≤ gs.length → SLP n| 0, _ => .nil| n + 1, hn =>let P := SLP.ofGateListAux gs hwf n (Nat.le_of_lt hn)let g := gs[n]'hnlet hg := hwf n hnP.snoc g.op ⟨g.i, hg.1⟩ ⟨g.j, hg.2⟩/-- Convert a well-formed gate list `gs` back into an `SLP gs.length`. -/def SLP.ofGateList (gs : List GateSpec) (hwf : WellFormed gs) : SLP gs.length :=SLP.ofGateListAux gs hwf gs.length le_rfltheorem SLP.evalWire_ofGateListAux (gs : List GateSpec) (hwf : WellFormed gs) :∀ (n : ℕ) (hn : n ≤ gs.length) (k : Fin (n + 2)),(SLP.ofGateListAux gs hwf n hn).evalWire k = (wireVals (gs.take n)).getD k.val 0| 0, _, k => bysimp only [SLP.ofGateListAux, SLP.evalWire, List.take_zero, wireVals, wireValsAux]rcases k with ⟨kv, hkv⟩rcases kv with _ | _ | kv· simp [List.getD]· simp [List.getD]· omega| n + 1, hn, k => bysimp only [SLP.ofGateListAux, SLP.evalWire]have htake : gs.take (n + 1) = gs.take n ++ [gs[n]'hn] := byrw [List.take_add_one, List.getElem?_eq_getElem (Nat.lt_of_succ_le hn)]rflhave hlen : (wireVals (gs.take n)).length = n + 2 := byrw [wireVals_length, List.length_take, Nat.min_eq_left (Nat.le_of_lt hn)]split_ifs with hk· rw [SLP.evalWire_ofGateListAux gs hwf n (Nat.le_of_lt hn) ⟨k.val, hk⟩,htake, wireVals_snoc, getD_append_left _ _ _ (hk.trans_eq hlen.symm)]· have hk_eq : k.val = n + 2 := by omegarw [htake, wireVals_snoc, getD_append_right _ _ _ (by omega)]simp only [hlen, hk_eq, Nat.sub_self]rw [getD_eq_getElem_of_lt _ _ (by simp), List.getElem_singleton]rw [SLP.evalWire_ofGateListAux gs hwf n (Nat.le_of_lt hn),SLP.evalWire_ofGateListAux gs hwf n (Nat.le_of_lt hn)]theorem SLP.evalPoly_ofGateList (gs : List GateSpec) (hwf : WellFormed gs) :(SLP.ofGateList gs hwf).evalPoly = output gs := byhave h := SLP.evalWire_ofGateListAux gs hwf gs.length le_rfl ⟨gs.length + 1, Nat.lt_succ_self _⟩simpa [SLP.ofGateList, SLP.evalPoly, output] using h/-! ## 2. Canonical Predicate -//-- Canonical numeric index of an `SLPOp` (`add = 0`, `sub = 1`, `mul = 2`). -/def SLPOp.idx : SLPOp → ℕ| .add => 0| .sub => 1| .mul => 2/-- Operand-order condition `(ord)` for a single gate:`i < j` for subtraction, `i ≤ j` for addition and multiplication. -/def GateSpec.Ord (g : GateSpec) : Prop :=match g.op with| .sub => g.i < g.j| .add | .mul => g.i ≤ g.j/-- Lexicographic `≤` comparison on `(op.idx, i, j)` triples. -/def GateSpec.keyLe (g₁ g₂ : GateSpec) : Prop :=g₁.op.idx < g₂.op.idx ∨(g₁.op.idx = g₂.op.idx ∧ (g₁.i < g₂.i ∨ (g₁.i = g₂.i ∧ g₁.j ≤ g₂.j)))/-- Strict lexicographic `<` comparison on `(op.idx, i, j)` triples. -/def GateSpec.keyLt (g₁ g₂ : GateSpec) : Prop :=g₁.op.idx < g₂.op.idx ∨(g₁.op.idx = g₂.op.idx ∧ (g₁.i < g₂.i ∨ (g₁.i = g₂.i ∧ g₁.j < g₂.j)))/-- Base-32 packed integer key `op * 1024 + i * 32 + j` used by the C enumeratorwhen wire indices are `< 32` (which holds whenever `gs.length ≤ 30` and `WellFormed gs`). -/def GateSpec.key32 (g : GateSpec) : ℕ :=g.op.idx * 1024 + g.i * 32 + g.jtheorem GateSpec.not_keyLe_iff {g₁ g₂ : GateSpec} : ¬ g₁.keyLe g₂ ↔ g₂.keyLt g₁ := byunfold GateSpec.keyLe GateSpec.keyLtomegatheorem GateSpec.keyLe_iff_key32 {g₁ g₂ : GateSpec}(hi₁ : g₁.i < 32) (hj₁ : g₁.j < 32) (hi₂ : g₂.i < 32) (hj₂ : g₂.j < 32) :g₁.keyLe g₂ ↔ g₁.key32 ≤ g₂.key32 := byunfold GateSpec.keyLe GateSpec.key32omega/-- Every gate in `gs` satisfies the operand-order condition `(ord)`. -/def OrdCanonical (gs : List GateSpec) : Prop :=∀ (k : ℕ) (hk : k < gs.length), gs[k].Ord/-- Every gate wire `k + 2` in `gs` evaluates to a nonzero polynomial `(nonzero)`. -/def NonzeroWires (gs : List GateSpec) : Prop :=∀ (k : ℕ) (hk : k < gs.length), (wireVals gs).getD (k + 2) 0 ≠ 0/-- No gate wire `k + 2` duplicates an earlier wire `m < k + 2` up to sign `(nodup)`. -/def NodupWires (gs : List GateSpec) : Prop :=∀ (k : ℕ) (hk : k < gs.length) (m : ℕ), m < k + 2 →(wireVals gs).getD (k + 2) 0 ≠ (wireVals gs).getD m 0 ∧(wireVals gs).getD (k + 2) 0 ≠ -((wireVals gs).getD m 0)/-- Every gate except the last is an operand of at least one later gate `(used)`. -/def UsedGates (gs : List GateSpec) : Prop :=∀ (k : ℕ), k + 1 < gs.length →∃ (k' : ℕ) (hk' : k' < gs.length), k < k' ∧ (gs[k'].i = k + 2 ∨ gs[k'].j = k + 2)/-- For every non-final gate `k` (`1 ≤ k ≤ n - 2`) that does not use gate `k - 1`(wire `k + 1`), the key triple of gate `k - 1` precedes or equals that of gate `k` `(lex)`. -/def LexOrdered (gs : List GateSpec) : Prop :=∀ (k : ℕ), 1 ≤ k → k + 1 < gs.length →(h1 : k - 1 < gs.length) → (h2 : k < gs.length) →gs[k].i ≠ k + 1 → gs[k].j ≠ k + 1 → (gs[k - 1]'h1).keyLe (gs[k]'h2)/-- Complete canonicality predicate matching the exhaustive enumerator. -/structure Canonical (gs : List GateSpec) : Prop wherewf : WellFormed gsord : OrdCanonical gsnonzero : NonzeroWires gsnodup : NodupWires gsused : UsedGates gslex : LexOrdered gs/-! ## 3. Reduction Lemmas Toward `exists_canonical` -//-- Target predicate: `gs` computes `f` or `-f`. -/def ComputesSigned (f : Polynomial ℤ) (gs : List GateSpec) : Prop :=output gs = f ∨ output gs = -fprivate noncomputable def sgnVal (b : Bool) : Polynomial ℤ :=if b then -1 else 1private lemma sgnVal_mul_self (b : Bool) : sgnVal b * sgnVal b = 1 := bycases b <;> simp [sgnVal]private lemma sgnVal_xor (b₁ b₂ : Bool) : sgnVal (xor b₁ b₂) = sgnVal b₁ * sgnVal b₂ := bycases b₁ <;> cases b₂ <;> simp [sgnVal]private lemma sgnVal_not (b : Bool) : sgnVal (!b) = -sgnVal b := bycases b <;> simp [sgnVal]private lemma sgnVal_ne_zero (b : Bool) : sgnVal b ≠ 0 := bycases b <;> simp [sgnVal]private def flipAddSub : SLPOp → SLPOp| .add => .sub| .sub => .add| .mul => .mulprivate lemma applyPoly_signed_combine (op : SLPOp) (s₁ s₂ : Bool) (a b : Polynomial ℤ) :(match op with| .mul => sgnVal (xor s₁ s₂) * (a * b)| .add => sgnVal s₁ * ((if s₁ = s₂ then op else flipAddSub op).applyPoly a b)| .sub => sgnVal s₁ * ((if s₁ = s₂ then op else flipAddSub op).applyPoly a b)) =op.applyPoly (sgnVal s₁ * a) (sgnVal s₂ * b) := bycases op <;> cases s₁ <;> cases s₂ <;>simp [sgnVal, flipAddSub, SLPOp.applyPoly] <;> ringprivate def shiftDown (k w : ℕ) : ℕ :=if k + 2 < w then w - 1 else wprivate lemma shiftDown_lt {k m w : ℕ} (hm : k ≤ m) (hw : w < m + 3) (hne : w ≠ k + 2) :shiftDown k w < m + 2 := byunfold shiftDownsplit_ifs <;> omegaprivate lemma shiftDown_inv {k w : ℕ} (hne : w ≠ k + 2) :(if shiftDown k w < k + 2 then shiftDown k w else shiftDown k w + 1) = w := byunfold shiftDownsplit_ifs <;> omega/-- Delete unused gate `k` (`k + 1 < gs.length`) and shift wire indices `> k + 2` down by `1`. -/private def deleteUnused (gs : List GateSpec) (k : ℕ) : List GateSpec :=List.ofFn (fun m : Fin (gs.length - 1) =>if m.val < k thengs[m.val]'(by omega)elselet g := gs[m.val + 1]'(by omega)⟨g.op, shiftDown k g.i, shiftDown k g.j⟩)private lemma deleteUnused_length (gs : List GateSpec) (k : ℕ) :(deleteUnused gs k).length = gs.length - 1 := bysimp [deleteUnused]private lemma deleteUnused_wellFormed {gs : List GateSpec} (hwf : WellFormed gs){k : ℕ} (hdead : ∀ (k' : ℕ) (hk' : k' < gs.length), k < k' → gs[k'].i ≠ k + 2 ∧ gs[k'].j ≠ k + 2) :WellFormed (deleteUnused gs k) := byintro m hmrw [deleteUnused_length] at hmsimp only [deleteUnused, List.getElem_ofFn]split_ifs with hmk· exact hwf m (by omega)· have hm1 : m + 1 < gs.length := by omegahave hgm := hwf (m + 1) hm1have hd := hdead (m + 1) hm1 (by omega)exact ⟨shiftDown_lt (by omega) hgm.1 hd.1, shiftDown_lt (by omega) hgm.2 hd.2⟩private lemma deleteUnused_wireVals {gs : List GateSpec} (hwf : WellFormed gs){k : ℕ} (hk : k + 1 < gs.length)(hdead : ∀ (k' : ℕ) (hk' : k' < gs.length), k < k' → gs[k'].i ≠ k + 2 ∧ gs[k'].j ≠ k + 2) :∀ (w : ℕ), w < (deleteUnused gs k).length + 2 →(wireVals (deleteUnused gs k)).getD w 0 =(wireVals gs).getD (if w < k + 2 then w else w + 1) 0 := byhave hwf' := deleteUnused_wellFormed hwf hdeadintro winduction w using Nat.strongRecOn with| ind w ih =>intro hwrcases w with _ | _ | m· rw [if_pos (by omega), wireVals_zero, wireVals_zero]· change (wireVals (deleteUnused gs k)).getD 1 0 =(wireVals gs).getD (if 1 < k + 2 then 1 else 1 + 1) 0rw [if_pos (by omega), wireVals_one, wireVals_one]· have hm : m < (deleteUnused gs k).length := by omegahave hm' : m < gs.length - 1 := by simpa [deleteUnused_length] using hmrw [wireVals_gate_wf hwf' hm]have hi_lt := (hwf' m hm).1have hj_lt := (hwf' m hm).2rw [ih _ hi_lt (by omega), ih _ hj_lt (by omega)]by_cases hmk : m < k· have hg_eq : (deleteUnused gs k)[m] = gs[m]'(by omega) := bysimp [deleteUnused, hmk]have hm_lt : m < gs.length := by omegahave hmi : gs[m].i < k + 2 := (hwf m hm_lt).1.trans_le (by omega)have hmj : gs[m].j < k + 2 := (hwf m hm_lt).2.trans_le (by omega)rw [hg_eq, if_pos hmi, if_pos hmj, if_pos (by omega), wireVals_gate_wf hwf hm_lt]· have hm1 : m + 1 < gs.length := by omegahave hd := hdead (m + 1) hm1 (by omega)have hg_eq : (deleteUnused gs k)[m] =⟨(gs[m + 1]'hm1).op, shiftDown k (gs[m + 1]'hm1).i, shiftDown k (gs[m + 1]'hm1).j⟩ := bysimp [deleteUnused, hmk]rw [hg_eq, shiftDown_inv hd.1, shiftDown_inv hd.2, if_neg (by omega),wireVals_gate_wf hwf hm1]private lemma deleteUnused_output {gs : List GateSpec} (hwf : WellFormed gs){k : ℕ} (hk : k + 1 < gs.length)(hdead : ∀ (k' : ℕ) (hk' : k' < gs.length), k < k' → gs[k'].i ≠ k + 2 ∧ gs[k'].j ≠ k + 2) :output (deleteUnused gs k) = output gs := byhave hlen : (deleteUnused gs k).length = gs.length - 1 := deleteUnused_length gs khave h := deleteUnused_wireVals hwf hk hdead ((deleteUnused gs k).length + 1) (by omega)have hge : ¬ ((deleteUnused gs k).length + 1 < k + 2) := by omegahave heq : (deleteUnused gs k).length + 1 + 1 = gs.length + 1 := by omegasimpa [output, hge, heq] using h/-- Sign tracking function for redirecting wire `k + 2` to `(m, flip)` (`m < k + 2`)and deleting gate `k` (`k + 1 < gs.length`). Here `w` is the new wire index. -/private def redirSign (gs : List GateSpec) (k m : ℕ) (flip : Bool) : ℕ → Bool| 0 => false| 1 => false| idx + 2 =>if hidx : idx < k thenfalseelse if hlen : idx + 1 < gs.length thenlet g := gs[idx + 1]'hlenlet si : Bool :=if g.i < k + 2 then falseelse if g.i = k + 2 then flipelse if g.i - 1 < idx + 2 then redirSign gs k m flip (g.i - 1)else falsematch g.op with| .mul =>let sj : Bool :=if g.j < k + 2 then falseelse if g.j = k + 2 then flipelse if g.j - 1 < idx + 2 then redirSign gs k m flip (g.j - 1)else falsexor si sj| .add | .sub => sielse falsetermination_by w => wdecreasing_by all_goals omegaprivate lemma redirSign_lt {gs : List GateSpec} {k m : ℕ} {flip : Bool}{w : ℕ} (hw : w < k + 2) : redirSign gs k m flip w = false := byrcases w with _ | _ | idx· simp [redirSign]· simp [redirSign]· unfold redirSignsimp [show idx < k by omega]private def redirOperand (gs : List GateSpec) (k m : ℕ) (flip : Bool) (u : ℕ) : ℕ × Bool :=if u < k + 2 then (u, false)else if u = k + 2 then (m, flip)else (u - 1, redirSign gs k m flip (u - 1))private lemma redirOperand_idx_lt {k m idx u : ℕ} {gs : List GateSpec} {flip : Bool}(hk : k ≤ idx) (hm : m < k + 2) (hu : u < idx + 3) :(redirOperand gs k m flip u).1 < idx + 2 := byunfold redirOperandsplit_ifs <;> omegaprivate def redirGate (gs : List GateSpec) (k m : ℕ) (flip : Bool) : List GateSpec :=List.ofFn (fun idx : Fin (gs.length - 1) =>if idx.val < k thengs[idx.val]'(by omega)elselet g := gs[idx.val + 1]'(by omega)let p₁ := redirOperand gs k m flip g.ilet p₂ := redirOperand gs k m flip g.jlet op' :=match g.op with| .mul => .mul| .add | .sub => if p₁.2 = p₂.2 then g.op else flipAddSub g.op⟨op', p₁.1, p₂.1⟩)private lemma redirGate_length (gs : List GateSpec) (k m : ℕ) (flip : Bool) :(redirGate gs k m flip).length = gs.length - 1 := bysimp [redirGate]private lemma redirGate_wellFormed {gs : List GateSpec} (hwf : WellFormed gs){k m : ℕ} (hm : m < k + 2) (flip : Bool) :WellFormed (redirGate gs k m flip) := byintro idx hidxrw [redirGate_length] at hidxby_cases hk : idx < k· simp only [redirGate, List.getElem_ofFn, hk, ↓reduceIte]exact hwf idx (by omega)· simp only [redirGate, List.getElem_ofFn, hk, ↓reduceIte]have hidx1 : idx + 1 < gs.length := by omegahave hg := hwf (idx + 1) hidx1exact ⟨redirOperand_idx_lt (by omega) hm hg.1, redirOperand_idx_lt (by omega) hm hg.2⟩private lemma redirSign_succ_ge {gs : List GateSpec} (hwf : WellFormed gs){k m idx : ℕ} (hk : k ≤ idx) (hidx1 : idx + 1 < gs.length) (flip : Bool) :let g := gs[idx + 1]'hidx1let p₁ := redirOperand gs k m flip g.ilet p₂ := redirOperand gs k m flip g.jredirSign gs k m flip (idx + 2) =match g.op with| .mul => xor p₁.2 p₂.2| .add | .sub => p₁.2 := byintro g p₁ p₂have hgi : g.i - 1 < idx + 2 := byhave := (hwf (idx + 1) hidx1).1dsimp only [g]omegahave hgj : g.j - 1 < idx + 2 := byhave := (hwf (idx + 1) hidx1).2dsimp only [g]omegaconv_lhs => unfold redirSignrw [dif_neg (by omega), dif_pos hidx1]dsimp only [p₁, p₂, redirOperand, g] at hgi hgj ⊢cases (gs[idx + 1]'hidx1).op <;> simp only [hgi, hgj, ↓reduceIte] <;> split_ifs <;> rflprivate lemma redirGate_wireVals {gs : List GateSpec} (hwf : WellFormed gs){k m : ℕ} (hk : k + 1 < gs.length) (hm : m < k + 2) (flip : Bool)(hdup : (wireVals gs).getD (k + 2) 0 = sgnVal flip * (wireVals gs).getD m 0) :∀ (w : ℕ), w < (redirGate gs k m flip).length + 2 →(wireVals (redirGate gs k m flip)).getD w 0 =sgnVal (redirSign gs k m flip w) *(wireVals gs).getD (if w < k + 2 then w else w + 1) 0 := byhave hwf' := redirGate_wellFormed hwf hm flipintro winduction w using Nat.strongRecOn with| ind w ih =>intro hwrcases w with _ | _ | idx· rw [if_pos (by omega), wireVals_zero, wireVals_zero]simp [redirSign, sgnVal]· change (wireVals (redirGate gs k m flip)).getD 1 0 =sgnVal (redirSign gs k m flip 1) * (wireVals gs).getD (if 1 < k + 2 then 1 else 1 + 1) 0rw [if_pos (by omega), wireVals_one, wireVals_one]simp [redirSign, sgnVal]· have hidx_len : idx < (redirGate gs k m flip).length := by omegahave hidx1 : idx + 1 < gs.length := byrw [redirGate_length] at hidx_lenomegarw [wireVals_gate_wf hwf' hidx_len]by_cases hlt : idx < k· have hidx_gs : idx < gs.length := by omegahave hi : gs[idx].i < idx + 2 := (hwf idx hidx_gs).1have hj : gs[idx].j < idx + 2 := (hwf idx hidx_gs).2have hgi_k : gs[idx].i < k + 2 := by omegahave hgj_k : gs[idx].j < k + 2 := by omegahave hg_eq : (redirGate gs k m flip)[idx] = gs[idx] := bysimp [redirGate, hlt]rw [hg_eq]have ihi := ih gs[idx].i hi (by omega)have ihj := ih gs[idx].j hj (by omega)rw [if_pos hgi_k, redirSign_lt hgi_k] at ihirw [if_pos hgj_k, redirSign_lt hgj_k] at ihjrw [ihi, ihj, if_pos (show idx + 2 < k + 2 by omega),redirSign_lt (show idx + 2 < k + 2 by omega), wireVals_gate_wf hwf hidx_gs]simp [sgnVal]· have hk_le : k ≤ idx := by omegahave hgi : gs[idx + 1].i < idx + 3 := (hwf (idx + 1) hidx1).1have hgj : gs[idx + 1].j < idx + 3 := (hwf (idx + 1) hidx1).2have hg_eq : (redirGate gs k m flip)[idx] =let g := gs[idx + 1]let p₁ := redirOperand gs k m flip g.ilet p₂ := redirOperand gs k m flip g.jlet op' :=match g.op with| .mul => .mul| .add | .sub => if p₁.2 = p₂.2 then g.op else flipAddSub g.op⟨op', p₁.1, p₂.1⟩ := bysimp [redirGate, hlt]have h_op : ∀ (u : ℕ), u < idx + 3 →(wireVals gs).getD u 0 =sgnVal (redirOperand gs k m flip u).2 *(wireVals (redirGate gs k m flip)).getD (redirOperand gs k m flip u).1 0 := byintro u huunfold redirOperandsplit_ifs with hu1 hu2· have ihu := ih u (by omega) (by omega)rw [if_pos hu1, redirSign_lt hu1] at ihurw [ihu]simp [sgnVal]· subst hu2have ihm := ih m (by omega) (by omega)rw [if_pos hm, redirSign_lt hm] at ihmsimp only [sgnVal, Bool.false_eq_true, ↓reduceIte, one_mul] at ihmrw [hdup, ihm]· have ihu := ih (u - 1) (by omega) (by omega)have hge : ¬ (u - 1 < k + 2) := by omegahave hu_eq : u - 1 + 1 = u := by omegarw [if_neg hge, hu_eq] at ihurw [ihu, ← mul_assoc, sgnVal_mul_self, one_mul]have h1 := h_op gs[idx + 1].i hgihave h2 := h_op gs[idx + 1].j hgj-- Since sgnVal s ∈ {1, -1}, multiply both sides by sgnVal shave h1' : (wireVals (redirGate gs k m flip)).getD (redirOperand gs k m flip gs[idx + 1].i).1 0 =sgnVal (redirOperand gs k m flip gs[idx + 1].i).2 * (wireVals gs).getD gs[idx + 1].i 0 := byrw [h1, ← mul_assoc, sgnVal_mul_self, one_mul]have h2' : (wireVals (redirGate gs k m flip)).getD (redirOperand gs k m flip gs[idx + 1].j).1 0 =sgnVal (redirOperand gs k m flip gs[idx + 1].j).2 * (wireVals gs).getD gs[idx + 1].j 0 := byrw [h2, ← mul_assoc, sgnVal_mul_self, one_mul]--Wait: express old = sgn * new, then compute new = sgn * oldrw [hg_eq, if_neg (by omega)]have hs_eq := redirSign_succ_ge (m := m) hwf hk_le hidx1 flipdsimp only at hs_eq ⊢rw [hs_eq, wireVals_gate_wf hwf hidx1, h1, h2]-- Now simplify the goal: both sides are op' (new1) (new2) vs sgnVal (new_s) * op (sgn1 * new1) (sgn2 * new2)set a := (wireVals (redirGate gs k m flip)).getD (redirOperand gs k m flip gs[idx + 1].i).1 0set b := (wireVals (redirGate gs k m flip)).getD (redirOperand gs k m flip gs[idx + 1].j).1 0set s₁ := (redirOperand gs k m flip gs[idx + 1].i).2set s₂ := (redirOperand gs k m flip gs[idx + 1].j).2cases hop : gs[idx + 1].op <;> cases s₁ <;> cases s₂ <;>simp [sgnVal, flipAddSub, SLPOp.applyPoly] <;> ringprivate lemma redirGate_computesSigned {f : Polynomial ℤ} {gs : List GateSpec}(hwf : WellFormed gs) (hcomp : ComputesSigned f gs){k m : ℕ} (hk : k + 1 < gs.length) (hm : m < k + 2) (flip : Bool)(hdup : (wireVals gs).getD (k + 2) 0 = sgnVal flip * (wireVals gs).getD m 0) :ComputesSigned f (redirGate gs k m flip) := byhave hlen := redirGate_length gs k m fliphave h := redirGate_wireVals hwf hk hm flip hdup ((redirGate gs k m flip).length + 1) (by omega)have hge : ¬ ((redirGate gs k m flip).length + 1 < k + 2) := by omegahave heq : (redirGate gs k m flip).length + 1 + 1 = gs.length + 1 := by omegarw [if_neg hge, heq] at hchange output (redirGate gs k m flip) =sgnVal (redirSign gs k m flip ((redirGate gs k m flip).length + 1)) * output gs at hrcases hcomp with hcomp | hcomp <;>cases hs : redirSign gs k m flip ((redirGate gs k m flip).length + 1) <;>simp [ComputesSigned, h, hs, sgnVal, hcomp]/-- Sign tracking function for `ordNormalize`. `normSign gs w` is `true` iffnormalized wire `w` holds `- (wireVals gs)[w]`. -/private def normSign (gs : List GateSpec) : ℕ → Bool| 0 => false| 1 => false| k + 2 =>if hk : k < gs.length thenlet g := gs[k]'hklet s₁ := if g.i < k + 2 then normSign gs g.i else falselet s₂ := if g.j < k + 2 then normSign gs g.j else falsematch g.op with| .mul => xor s₁ s₂| .add | .sub =>let op₁ := if s₁ = s₂ then g.op else flipAddSub g.opif op₁ = .sub ∧ g.j < g.i then !s₁ else s₁else falsetermination_by w => wdecreasing_by all_goals omegaprivate def normGate (g : GateSpec) (s₁ s₂ : Bool) : GateSpec :=match g.op with| .mul => ⟨.mul, min g.i g.j, max g.i g.j⟩| .add | .sub =>let op₁ := if s₁ = s₂ then g.op else flipAddSub g.opmatch op₁ with| .add => ⟨.add, min g.i g.j, max g.i g.j⟩| .sub => if g.i ≤ g.j then ⟨.sub, g.i, g.j⟩ else ⟨.sub, g.j, g.i⟩| .mul => ⟨.mul, min g.i g.j, max g.i g.j⟩private def ordNormalize (gs : List GateSpec) : List GateSpec :=List.ofFn (fun k : Fin gs.length =>let g := gs[k.val]normGate g (normSign gs g.i) (normSign gs g.j))private lemma ordNormalize_length (gs : List GateSpec) :(ordNormalize gs).length = gs.length := bysimp [ordNormalize]private lemma normGate_operands (g : GateSpec) (s₁ s₂ : Bool) :((normGate g s₁ s₂).i = g.i ∧ (normGate g s₁ s₂).j = g.j) ∨((normGate g s₁ s₂).i = g.j ∧ (normGate g s₁ s₂).j = g.i) := byhave hminmax : (min g.i g.j = g.i ∧ max g.i g.j = g.j) ∨(min g.i g.j = g.j ∧ max g.i g.j = g.i) := byby_cases h : g.i ≤ g.j· exact Or.inl ⟨min_eq_left h, max_eq_right h⟩· exact Or.inr ⟨min_eq_right (Nat.le_of_not_ge h), max_eq_left (Nat.le_of_not_ge h)⟩cases hop : g.op <;> cases s₁ <;> cases s₂ <;>simp only [normGate, hop, flipAddSub, Bool.false_eq_true, Bool.true_eq_false, ↓reduceIte]all_goals first| exact hminmax| (by_cases hij : g.i ≤ g.j· simp [hij]· simp [hij])private lemma ordNormalize_wellFormed {gs : List GateSpec} (hwf : WellFormed gs) :WellFormed (ordNormalize gs) := byintro k hkrw [ordNormalize_length] at hkhave hg := hwf k hksimp only [ordNormalize, List.getElem_ofFn]rcases normGate_operands gs[k] (normSign gs gs[k].i) (normSign gs gs[k].j) with ⟨hi, hj⟩ | ⟨hi, hj⟩· rw [hi, hj]; exact hg· rw [hi, hj]; exact ⟨hg.2, hg.1⟩private lemma normGate_ord {g : GateSpec} {s₁ s₂ : Bool}(hne : ¬ ((if s₁ = s₂ then g.op else flipAddSub g.op) = .sub ∧ g.i = g.j)) :(normGate g s₁ s₂).Ord := byhave hmm : min g.i g.j ≤ max g.i g.j := le_trans (min_le_left _ _) (le_max_left _ _)have hne' : (if s₁ = s₂ then g.op else flipAddSub g.op) = .sub → g.i ≠ g.j :=fun h1 h2 => hne ⟨h1, h2⟩cases hop : g.op <;> cases s₁ <;> cases s₂ <;>simp only [normGate, hop, flipAddSub, Bool.false_eq_true, Bool.true_eq_false, ↓reduceIte] at hne' ⊢all_goals first| exact hmm| (by_cases hij : g.i ≤ g.j· simp only [hij, ↓reduceIte, GateSpec.Ord]have : g.i ≠ g.j := hne' trivialomega· simp only [hij, ↓reduceIte, GateSpec.Ord]omega)private lemma normGate_wire_eq {g : GateSpec} {s₁ s₂ : Bool}(hneq : ¬ ((if s₁ = s₂ then g.op else flipAddSub g.op) = .sub ∧ g.i = g.j))(new_i new_j : Polynomial ℤ) (heq : g.i = g.j → new_i = new_j) :let out_s :=match g.op with| .mul => xor s₁ s₂| .add | .sub =>let op₁ := if s₁ = s₂ then g.op else flipAddSub g.opif op₁ = .sub ∧ g.j < g.i then !s₁ else s₁let g' := normGate g s₁ s₂g'.op.applyPoly (if g'.i = g.i then new_i else new_j) (if g'.j = g.i then new_i else new_j) =sgnVal out_s * g.op.applyPoly (sgnVal s₁ * new_i) (sgnVal s₂ * new_j) := byby_cases hij_eq : g.i = g.j· have hnew : new_i = new_j := heq hij_eqsubst hnewcases hop : g.op <;> cases s₁ <;> cases s₂ <;>simp [normGate, flipAddSub, SLPOp.applyPoly, sgnVal, hop, hij_eq] at hneq ⊢ <;> ring· by_cases hij : g.i ≤ g.j· have hlt : g.i < g.j := by omegahave hnot_ji : ¬ (g.j < g.i) := by omegahave hne_ji : g.j ≠ g.i := by omegacases hop : g.op <;> cases s₁ <;> cases s₂ <;>simp [normGate, flipAddSub, SLPOp.applyPoly, sgnVal, hop, hij, hnot_ji, hne_ji,min_eq_left hij, max_eq_right hij] <;> ring· have hlt : g.j < g.i := by omegahave hji : g.j ≤ g.i := by omegahave hne_ji : g.j ≠ g.i := by omegacases hop : g.op <;> cases s₁ <;> cases s₂ <;>simp [normGate, flipAddSub, SLPOp.applyPoly, sgnVal, hop, hij, hlt, hne_ji,min_eq_right hji, max_eq_left hji] <;> ringprivate lemma ordNormalize_wireVals_and_ord {gs : List GateSpec}(hwf : WellFormed gs) (hnz : NonzeroWires gs) :(∀ (w : ℕ), w < gs.length + 2 →(wireVals (ordNormalize gs)).getD w 0 = sgnVal (normSign gs w) * (wireVals gs).getD w 0) ∧OrdCanonical (ordNormalize gs) := by-- Prove simultaneously by induction on w (and k for OrdCanonical)have hmain : ∀ (w : ℕ), w < gs.length + 2 →(wireVals (ordNormalize gs)).getD w 0 = sgnVal (normSign gs w) * (wireVals gs).getD w 0 := byintro winduction w using Nat.strongRecOn with| ind w ih =>intro hwrcases w with _ | _ | k· rw [wireVals_zero, wireVals_zero]; simp [normSign, sgnVal]· change (wireVals (ordNormalize gs)).getD 1 0 =sgnVal (normSign gs 1) * (wireVals gs).getD 1 0rw [wireVals_one, wireVals_one]; simp [normSign, sgnVal]· have hk : k < gs.length := by omegahave hk' : k < (ordNormalize gs).length := by rwa [ordNormalize_length]have hwf' := ordNormalize_wellFormed hwfhave hgi : gs[k].i < k + 2 := (hwf k hk).1have hgj : gs[k].j < k + 2 := (hwf k hk).2have h_old := wireVals_gate_wf hwf hkhave h_new := wireVals_gate_wf hwf' hk'have h_neq : ¬ ((if normSign gs gs[k].i = normSign gs gs[k].j then gs[k].opelse flipAddSub gs[k].op) = .sub ∧ gs[k].i = gs[k].j) := byintro ⟨hop_sub, hij⟩rw [hij, if_pos rfl] at hop_subhave h0 : (wireVals gs).getD (k + 2) 0 = 0 := byrw [h_old, hij, hop_sub]simp [SLPOp.applyPoly]exact hnz k hk h0have ihi_old := ih gs[k].i hgi (by omega)have ihj_old := ih gs[k].j hgj (by omega)have h_ng : (ordNormalize gs)[k] =normGate gs[k] (normSign gs gs[k].i) (normSign gs gs[k].j) := bysimp [ordNormalize]have h_normSign_k : normSign gs (k + 2) =match gs[k].op with| .mul => xor (normSign gs gs[k].i) (normSign gs gs[k].j)| .add | .sub =>let op₁ := if normSign gs gs[k].i = normSign gs gs[k].j then gs[k].opelse flipAddSub gs[k].opif op₁ = .sub ∧ gs[k].j < gs[k].i then !(normSign gs gs[k].i)else normSign gs gs[k].i := byconv_lhs => unfold normSignsimp [hk, hgi, hgj]set g := gs[k]set s₁ := normSign gs g.iset s₂ := normSign gs g.jset g' := normGate g s₁ s₂have h_mem_i : g'.i = g.i ∨ g'.i = g.j := byrcases normGate_operands g s₁ s₂ with ⟨h1, _⟩ | ⟨h1, _⟩· exact Or.inl h1· exact Or.inr h1have h_mem_j : g'.j = g.i ∨ g'.j = g.j := byrcases normGate_operands g s₁ s₂ with ⟨_, h2⟩ | ⟨_, h2⟩· exact Or.inr h2· exact Or.inl h2have h_new_i_old : (wireVals (ordNormalize gs)).getD g'.i 0 =if g'.i = g.i then (wireVals (ordNormalize gs)).getD g.i 0else (wireVals (ordNormalize gs)).getD g.j 0 := byrcases h_mem_i with h | h <;> split_ifs with h1 <;> simp_allhave h_new_j_old : (wireVals (ordNormalize gs)).getD g'.j 0 =if g'.j = g.i then (wireVals (ordNormalize gs)).getD g.i 0else (wireVals (ordNormalize gs)).getD g.j 0 := byrcases h_mem_j with h | h <;> split_ifs with h1 <;> simp_allrw [h_new, h_ng]change g'.op.applyPoly ((wireVals (ordNormalize gs)).getD g'.i 0)((wireVals (ordNormalize gs)).getD g'.j 0) =sgnVal (normSign gs (k + 2)) * (wireVals gs).getD (k + 2) 0rw [h_new_i_old, h_new_j_old]have hlem := normGate_wire_eq h_neq((wireVals (ordNormalize gs)).getD g.i 0)((wireVals (ordNormalize gs)).getD g.j 0)(fun hij => by rw [hij])dsimp only at hlemrw [hlem, ← h_normSign_k, ihi_old, ihj_old, h_old]have h_old_i : sgnVal s₁ * (sgnVal s₁ * (wireVals gs).getD g.i 0) =(wireVals gs).getD g.i 0 := byrw [← mul_assoc, sgnVal_mul_self, one_mul]have h_old_j : sgnVal s₂ * (sgnVal s₂ * (wireVals gs).getD g.j 0) =(wireVals gs).getD g.j 0 := byrw [← mul_assoc, sgnVal_mul_self, one_mul]change sgnVal (normSign gs (k + 2)) *g.op.applyPoly (sgnVal s₁ * (sgnVal s₁ * (wireVals gs).getD g.i 0))(sgnVal s₂ * (sgnVal s₂ * (wireVals gs).getD g.j 0)) =sgnVal (normSign gs (k + 2)) * g.op.applyPoly ((wireVals gs).getD g.i 0) ((wireVals gs).getD g.j 0)rw [h_old_i, h_old_j]refine ⟨hmain, ?_⟩intro k hkrw [ordNormalize_length] at hksimp only [ordNormalize, List.getElem_ofFn]apply normGate_ordintro ⟨hop_sub, hij⟩rw [hij, if_pos rfl] at hop_subhave h0 : (wireVals gs).getD (k + 2) 0 = 0 := byrw [wireVals_gate_wf hwf hk, hij, hop_sub]simp [SLPOp.applyPoly]exact hnz k hk h0private lemma ordNormalize_preserves_nonzero {gs : List GateSpec}(hwf : WellFormed gs) (hnz : NonzeroWires gs) :NonzeroWires (ordNormalize gs) := byintro k hkrw [ordNormalize_length] at hkrw [(ordNormalize_wireVals_and_ord hwf hnz).1 (k + 2) (by omega)]exact mul_ne_zero (sgnVal_ne_zero _) (hnz k hk)private lemma ordNormalize_preserves_nodup {gs : List GateSpec}(hwf : WellFormed gs) (hnz : NonzeroWires gs) (hnodup : NodupWires gs) :NodupWires (ordNormalize gs) := byintro k hk m hmrw [ordNormalize_length] at hkhave hvals := (ordNormalize_wireVals_and_ord hwf hnz).1rw [hvals (k + 2) (by omega), hvals m (by omega)]have hnd := hnodup k hk m hmcases hs1 : normSign gs (k + 2) <;> cases hs2 : normSign gs m <;> simp [sgnVal]· exact hnd· exact ⟨hnd.2, hnd.1⟩· exact ⟨fun h => hnd.2 (neg_eq_iff_eq_neg.mp h), fun h => hnd.1 h⟩· exact ⟨fun h => hnd.1 h, fun h => hnd.2 (neg_eq_iff_eq_neg.mp h)⟩private lemma ordNormalize_preserves_used {gs : List GateSpec}(hused : UsedGates gs) : UsedGates (ordNormalize gs) := byintro k hkrw [ordNormalize_length] at hkrcases hused k hk with ⟨k', hk', hkk', hor⟩refine ⟨k', by rwa [ordNormalize_length], hkk', ?_⟩simp only [ordNormalize, List.getElem_ofFn]rcases normGate_operands gs[k'] (normSign gs gs[k'].i) (normSign gs gs[k'].j) with⟨hi, hj⟩ | ⟨hi, hj⟩· rw [hi, hj]; exact hor· rw [hi, hj]; exact hor.symmprivate lemma ordNormalize_computesSigned {f : Polynomial ℤ} {gs : List GateSpec}(hwf : WellFormed gs) (hnz : NonzeroWires gs) (hcomp : ComputesSigned f gs) :ComputesSigned f (ordNormalize gs) := byhave h := (ordNormalize_wireVals_and_ord hwf hnz).1 (gs.length + 1) (by omega)have hlen := ordNormalize_length gshave hout : output (ordNormalize gs) = sgnVal (normSign gs (gs.length + 1)) * output gs := bysimpa [output, hlen] using hrcases hcomp with hcomp | hcomp <;>cases hs : normSign gs (gs.length + 1) <;>simp [ComputesSigned, hout, hs, sgnVal, hcomp]private lemma normSign_false_of_ord_prefix {gs : List GateSpec} (hwf : WellFormed gs){p : ℕ} (hp : p ≤ gs.length)(hord : ∀ (m : ℕ) (hm : m < p), (gs[m]'(by omega)).Ord) :∀ (w : ℕ), w < p + 2 → normSign gs w = false := byintro winduction w using Nat.strongRecOn with| ind w ih =>intro hwrcases w with _ | _ | m· simp [normSign]· simp [normSign]· have hm : m < p := by omegahave hm_gs : m < gs.length := by omegahave hgi : gs[m].i < m + 2 := (hwf m hm_gs).1have hgj : gs[m].j < m + 2 := (hwf m hm_gs).2have si_f : normSign gs gs[m].i = false := ih gs[m].i hgi (by omega)have sj_f : normSign gs gs[m].j = false := ih gs[m].j hgj (by omega)have hm_ord := hord m hmconv_lhs => unfold normSignsimp only [hm_gs, ↓reduceDIte, hgi, hgj, si_f, sj_f]cases hop : gs[m].op <;> simp [GateSpec.Ord, hop] at hm_ord ⊢omegaprivate lemma ordNormalize_prefix_eq {gs : List GateSpec} (hwf : WellFormed gs){p : ℕ} (hp : p ≤ gs.length)(hord : ∀ (m : ℕ) (hm : m < p), (gs[m]'(by omega)).Ord) :∀ (m : ℕ) (hm : m < p), (ordNormalize gs)[m]'(by rw [ordNormalize_length]; omega) = gs[m]'(by omega) := byintro m hmhave hm_gs : m < gs.length := by omegahave hgi : gs[m].i < m + 2 := (hwf m hm_gs).1have hgj : gs[m].j < m + 2 := (hwf m hm_gs).2have si_f : normSign gs gs[m].i = false := normSign_false_of_ord_prefix hwf hp hord gs[m].i (by omega)have sj_f : normSign gs gs[m].j = false := normSign_false_of_ord_prefix hwf hp hord gs[m].j (by omega)have hm_ord := hord m hmsimp only [ordNormalize, List.getElem_ofFn, si_f, sj_f]rcases hg : gs[m] with ⟨op, i, j⟩rw [hg] at hm_ordcases op <;> simp only [normGate, ↓reduceIte, GateSpec.Ord] at hm_ord ⊢· simp [min_eq_left hm_ord, max_eq_right hm_ord]· simp [hm_ord.le]· simp [min_eq_left hm_ord, max_eq_right hm_ord]/-- Swap wires `a` and `b`, fixing all other indices. -/private def swapIdx (a b x : ℕ) : ℕ :=if x = a then b else if x = b then a else xprivate lemma swapIdx_invol (a b x : ℕ) : swapIdx a b (swapIdx a b x) = x := byunfold swapIdxsplit_ifs <;> omegaprivate lemma swapIdx_lt {a b m x : ℕ} (ha : a < m) (hb : b < m) (hx : x < m) :swapIdx a b x < m := byunfold swapIdxsplit_ifs <;> omegaprivate lemma swapIdx_lt_of_lt {a b x : ℕ} (hx1 : x < a) (hx2 : x < b) :swapIdx a b x = x := byunfold swapIdxsplit_ifs <;> omega/-- Swap independent adjacent gates `k - 1` and `k` (`1 ≤ k`, `k + 1 < gs.length`)and swap wire references `k + 1 ↔ k + 2` in all gates `> k`. -/private def swapRaw (gs : List GateSpec) (k : ℕ) : List GateSpec :=List.ofFn (fun m : Fin gs.length =>if m.val = k - 1 thengs[k]!else if m.val = k thengs[k - 1]!else if m.val < k - 1 thengs[m.val]elselet g := gs[m.val]⟨g.op, swapIdx (k + 1) (k + 2) g.i, swapIdx (k + 1) (k + 2) g.j⟩)private lemma swapRaw_length (gs : List GateSpec) (k : ℕ) :(swapRaw gs k).length = gs.length := bysimp [swapRaw]private lemma swapRaw_wellFormed {gs : List GateSpec} (hwf : WellFormed gs){k : ℕ} (hk1 : 1 ≤ k) (hk2 : k + 1 < gs.length)(hind_i : gs[k].i ≠ k + 1) (hind_j : gs[k].j ≠ k + 1) :WellFormed (swapRaw gs k) := byintro m hmrw [swapRaw_length] at hmsimp only [swapRaw, List.getElem_ofFn]split_ifs with h1 h2 h3· have hgk := hwf k (by omega)have heq : gs[k]! = gs[k] := by simp [show k < gs.length by omega]rw [heq]omega· have hgk1 := hwf (k - 1) (by omega)have heq : gs[k - 1]! = gs[k - 1] := by simp [show k - 1 < gs.length by omega]rw [heq]omega· exact hwf m hm· have hgm := hwf m hmhave hk_lt : k + 1 < m + 2 := by omegahave hk2_lt : k + 2 < m + 2 := by omegaexact ⟨swapIdx_lt hk_lt hk2_lt hgm.1, swapIdx_lt hk_lt hk2_lt hgm.2⟩private lemma swapRaw_wireVals {gs : List GateSpec} (hwf : WellFormed gs){k : ℕ} (hk1 : 1 ≤ k) (hk2 : k + 1 < gs.length)(hind_i : gs[k].i ≠ k + 1) (hind_j : gs[k].j ≠ k + 1) :∀ (w : ℕ), w < gs.length + 2 →(wireVals (swapRaw gs k)).getD w 0 = (wireVals gs).getD (swapIdx (k + 1) (k + 2) w) 0 := byhave hwf' := swapRaw_wellFormed hwf hk1 hk2 hind_i hind_jintro winduction w using Nat.strongRecOn with| ind w ih =>intro hwrcases w with _ | _ | m· have h0 : swapIdx (k + 1) (k + 2) 0 = 0 := swapIdx_lt_of_lt (by omega) (by omega)rw [h0, wireVals_zero, wireVals_zero]· have h1 : swapIdx (k + 1) (k + 2) 1 = 1 := swapIdx_lt_of_lt (by omega) (by omega)change (wireVals (swapRaw gs k)).getD 1 0 = (wireVals gs).getD (swapIdx (k + 1) (k + 2) 1) 0rw [h1, wireVals_one, wireVals_one]· have hm : m < gs.length := by omegahave hm' : m < (swapRaw gs k).length := by rwa [swapRaw_length]rw [wireVals_gate_wf hwf' hm']have hi' := (hwf' m hm').1have hj' := (hwf' m hm').2rw [ih _ hi' (by omega), ih _ hj' (by omega)]simp only [swapRaw, List.getElem_ofFn]split_ifs with h1 h2 h3· have heq : gs[k]! = gs[k] := by simp [show k < gs.length by omega]rw [heq]have hgk := hwf k (by omega)have hsi : swapIdx (k + 1) (k + 2) gs[k].i = gs[k].i :=swapIdx_lt_of_lt (by omega) (by omega)have hsj : swapIdx (k + 1) (k + 2) gs[k].j = gs[k].j :=swapIdx_lt_of_lt (by omega) (by omega)have hsw : swapIdx (k + 1) (k + 2) (m + 2) = k + 2 := byunfold swapIdx; split_ifs <;> omegarw [hsi, hsj, hsw, ← wireVals_gate_wf hwf (show k < gs.length by omega)]· have heq : gs[k - 1]! = gs[k - 1] := by simp [show k - 1 < gs.length by omega]rw [heq]have hgk1 := hwf (k - 1) (by omega)have hsi : swapIdx (k + 1) (k + 2) gs[k - 1].i = gs[k - 1].i :=swapIdx_lt_of_lt (by omega) (by omega)have hsj : swapIdx (k + 1) (k + 2) gs[k - 1].j = gs[k - 1].j :=swapIdx_lt_of_lt (by omega) (by omega)have hsw : swapIdx (k + 1) (k + 2) (m + 2) = k + 1 := byunfold swapIdx; split_ifs <;> omegahave hk1_eq : (k - 1) + 2 = k + 1 := by omegarw [hsi, hsj, hsw, ← hk1_eq, ← wireVals_gate_wf hwf (show k - 1 < gs.length by omega)]· have hgm := hwf m hmhave hsi : swapIdx (k + 1) (k + 2) gs[m].i = gs[m].i :=swapIdx_lt_of_lt (by omega) (by omega)have hsj : swapIdx (k + 1) (k + 2) gs[m].j = gs[m].j :=swapIdx_lt_of_lt (by omega) (by omega)have hsw : swapIdx (k + 1) (k + 2) (m + 2) = m + 2 :=swapIdx_lt_of_lt (by omega) (by omega)rw [hsi, hsj, hsw, ← wireVals_gate_wf hwf hm]· dsimp onlyrw [swapIdx_invol, swapIdx_invol]have hsw : swapIdx (k + 1) (k + 2) (m + 2) = m + 2 := byunfold swapIdx; split_ifs <;> omegarw [hsw, ← wireVals_gate_wf hwf hm]private lemma swapRaw_preserves_nonzero {gs : List GateSpec} (hwf : WellFormed gs)(hnz : NonzeroWires gs) {k : ℕ} (hk1 : 1 ≤ k) (hk2 : k + 1 < gs.length)(hind_i : gs[k].i ≠ k + 1) (hind_j : gs[k].j ≠ k + 1) :NonzeroWires (swapRaw gs k) := byintro m hmrw [swapRaw_length] at hmrw [swapRaw_wireVals hwf hk1 hk2 hind_i hind_j (m + 2) (by omega)]have hlt : swapIdx (k + 1) (k + 2) (m + 2) < gs.length + 2 :=swapIdx_lt (by omega) (by omega) (by omega)have hge2 : 2 ≤ swapIdx (k + 1) (k + 2) (m + 2) := byunfold swapIdx; split_ifs <;> omegahave heq : swapIdx (k + 1) (k + 2) (m + 2) = (swapIdx (k + 1) (k + 2) (m + 2) - 2) + 2 := by omegarw [heq]exact hnz _ (by omega)private lemma swapRaw_preserves_nodup {gs : List GateSpec} (hwf : WellFormed gs)(hnodup : NodupWires gs) {k : ℕ} (hk1 : 1 ≤ k) (hk2 : k + 1 < gs.length)(hind_i : gs[k].i ≠ k + 1) (hind_j : gs[k].j ≠ k + 1) :NodupWires (swapRaw gs k) := byintro m hm u hurw [swapRaw_length] at hmhave hw := swapRaw_wireVals hwf hk1 hk2 hind_i hind_jrw [hw (m + 2) (by omega), hw u (by omega)]by_cases hmk : m = k· -- new wire k+2 holds old wire k+1; u < k+2 => either u < k+1 or u = k+1 (holds old k+2)subst mhave hsw1 : swapIdx (k + 1) (k + 2) (k + 2) = k + 1 := by unfold swapIdx; split_ifs <;> omegarw [hsw1]by_cases huk : u = k + 1· subst uhave hsw2 : swapIdx (k + 1) (k + 2) (k + 1) = k + 2 := by unfold swapIdx; split_ifs <;> omegarw [hsw2]have hnd := hnodup k (by omega) (k + 1) (by omega)constructor <;> intro h· exact hnd.1 h.symm· exact hnd.2 (neg_eq_iff_eq_neg.mp h.symm)· have hu_lt : u < k + 1 := by omegahave hsw2 : swapIdx (k + 1) (k + 2) u = u := swapIdx_lt_of_lt hu_lt (by omega)rw [hsw2]have hk1_eq : (k - 1) + 2 = k + 1 := by omegarw [← hk1_eq]exact hnodup (k - 1) (by omega) u (by omega)· by_cases hmk1 : m = k - 1· -- new wire k+1 holds old wire k+2; u < k+1 => swapIdx u = u < k+2have hsw1 : swapIdx (k + 1) (k + 2) (m + 2) = k + 2 := byunfold swapIdx; split_ifs <;> omegahave hsw2 : swapIdx (k + 1) (k + 2) u = u := swapIdx_lt_of_lt (by omega) (by omega)rw [hsw1, hsw2]exact hnodup k (by omega) u (by omega)· by_cases hlt : m < k - 1· have hsw1 : swapIdx (k + 1) (k + 2) (m + 2) = m + 2 :=swapIdx_lt_of_lt (by omega) (by omega)have hsw2 : swapIdx (k + 1) (k + 2) u = u :=swapIdx_lt_of_lt (by omega) (by omega)rw [hsw1, hsw2]exact hnodup m hm u hu· -- m > k, so m + 2 >= k + 3have hm_gt : k < m := by omegahave hsw1 : swapIdx (k + 1) (k + 2) (m + 2) = m + 2 := byunfold swapIdx; split_ifs <;> omegahave hu_lt : swapIdx (k + 1) (k + 2) u < m + 2 :=swapIdx_lt (by omega) (by omega) hurw [hsw1]exact hnodup m hm _ hu_ltprivate lemma swapRaw_preserves_used {gs : List GateSpec} (hused : UsedGates gs){k : ℕ} (hk1 : 1 ≤ k) (hk2 : k + 1 < gs.length)(hind_i : gs[k].i ≠ k + 1) (hind_j : gs[k].j ≠ k + 1) :UsedGates (swapRaw gs k) := byintro u hurw [swapRaw_length] at huhave hlen : (swapRaw gs k).length = gs.length := swapRaw_length gs kby_cases huk : u = k· -- new wire k + 2 corresponds to old gate k - 1 (wire k + 1).-- Its user in gs cannot be gate k (by hind_i, hind_j), so it must be some m > k.subst urcases hused (k - 1) (by omega) with ⟨m, hm, hkm, hor⟩have hm_gt : k < m := byby_contra hlehave hmk : m = k := by omegasubst mrcases hor with hi | hj· exact hind_i (by omega)· exact hind_j (by omega)refine ⟨m, by omega, hm_gt, ?_⟩simp only [swapRaw, List.getElem_ofFn]rw [if_neg (by omega), if_neg (by omega), if_neg (by omega)]have hsw : swapIdx (k + 1) (k + 2) (k + 1) = k + 2 := by unfold swapIdx; split_ifs <;> omegarcases hor with hi | hj· left; dsimp; rw [show (k - 1) + 2 = k + 1 by omega] at hi; rw [hi, hsw]· right; dsimp; rw [show (k - 1) + 2 = k + 1 by omega] at hj; rw [hj, hsw]· by_cases huk1 : u = k - 1· -- new wire k + 1 corresponds to old gate k (wire k + 2); since k + 1 < gs.length, used by m > krcases hused k hk2 with ⟨m, hm, hkm, hor⟩refine ⟨m, by omega, by omega, ?_⟩simp only [swapRaw, List.getElem_ofFn]rw [if_neg (by omega), if_neg (by omega), if_neg (by omega)]have hsw : swapIdx (k + 1) (k + 2) (k + 2) = k + 1 := by unfold swapIdx; split_ifs <;> omegahave hu2 : u + 2 = k + 1 := by omegarw [hu2]rcases hor with hi | hj· left; dsimp; rw [hi, hsw]· right; dsimp; rw [hj, hsw]· by_cases hlt : u < k - 1· rcases hused u (by omega) with ⟨m, hm, hum, hor⟩by_cases hmk : m = k· subst mrefine ⟨k - 1, by omega, by omega, ?_⟩have hget : (swapRaw gs k)[k - 1]'(by omega) = gs[k]'(by omega) := bysimp [swapRaw, show k < gs.length by omega]rw [hget]; exact hor· by_cases hmk1 : m = k - 1· refine ⟨k, by omega, by omega, ?_⟩have hne : k ≠ k - 1 := by omegahave hget : (swapRaw gs k)[k]'(by omega) = gs[k - 1]'(by omega) := bysimp [swapRaw, hne, show k - 1 < gs.length by omega]rw [hget]subst mexact hor· by_cases hm_lt : m < k - 1· refine ⟨m, by omega, hum, ?_⟩have hget : (swapRaw gs k)[m]'(by omega) = gs[m]'(by omega) := bysimp [swapRaw, show m ≠ k - 1 by omega, show m ≠ k by omega, hm_lt]rw [hget]exact hor· have hm_gt : k < m := by omegarefine ⟨m, by omega, hum, ?_⟩have hget : (swapRaw gs k)[m]'(by omega) =⟨gs[m].op, swapIdx (k + 1) (k + 2) gs[m].i, swapIdx (k + 1) (k + 2) gs[m].j⟩ := bysimp [swapRaw, show m ≠ k - 1 by omega, show m ≠ k by omega, hm_lt]rw [hget]have hsw : swapIdx (k + 1) (k + 2) (u + 2) = u + 2 := swapIdx_lt_of_lt (by omega) (by omega)rcases hor with hi | hj· left; rw [hi, hsw]· right; rw [hj, hsw]· -- u > khave hu_gt : k < u := by omegarcases hused u hu with ⟨m, hm, hum, hor⟩refine ⟨m, by omega, hum, ?_⟩have hget : (swapRaw gs k)[m]'(by omega) =⟨gs[m].op, swapIdx (k + 1) (k + 2) gs[m].i, swapIdx (k + 1) (k + 2) gs[m].j⟩ := bysimp [swapRaw, show m ≠ k - 1 by omega, show m ≠ k by omega, show ¬ m < k - 1 by omega]rw [hget]have hsw : swapIdx (k + 1) (k + 2) (u + 2) = u + 2 := byunfold swapIdx; split_ifs <;> omegarcases hor with hi | hj· left; rw [hi, hsw]· right; rw [hj, hsw]private lemma swapRaw_computesSigned {f : Polynomial ℤ} {gs : List GateSpec}(hwf : WellFormed gs) (hcomp : ComputesSigned f gs){k : ℕ} (hk1 : 1 ≤ k) (hk2 : k + 1 < gs.length)(hind_i : gs[k].i ≠ k + 1) (hind_j : gs[k].j ≠ k + 1) :ComputesSigned f (swapRaw gs k) := byhave h := swapRaw_wireVals hwf hk1 hk2 hind_i hind_j (gs.length + 1) (by omega)have hsw : swapIdx (k + 1) (k + 2) (gs.length + 1) = gs.length + 1 := byunfold swapIdx; split_ifs <;> omegarw [hsw] at hhave hout : output (swapRaw gs k) = output gs := bysimpa [output, swapRaw_length] using hsimpa [ComputesSigned, hout] using hcompprivate lemma swapRaw_ord_prefix {gs : List GateSpec} (hord : OrdCanonical gs){k : ℕ} (hk1 : 1 ≤ k) (hk2 : k + 1 < gs.length) :∀ (m : ℕ) (hm : m < k + 1),((swapRaw gs k)[m]'(by rw [swapRaw_length]; omega)).Ord := byintro m hmsimp only [swapRaw, List.getElem_ofFn]split_ifs with h1 h2 h3· have heq : gs[k]! = gs[k] := by simp [show k < gs.length by omega]rw [heq]; exact hord k (by omega)· have heq : gs[k - 1]! = gs[k - 1] := by simp [show k - 1 < gs.length by omega]rw [heq]; exact hord (k - 1) (by omega)· exact hord m (by omega)· omega/-! ### Weight Function for Lexicographic Minimization at Fixed Length -/private def keyCode (M : ℕ) (g : GateSpec) : ℕ :=g.op.idx * M * M + g.i * M + g.jprivate lemma keyCode_lt {M : ℕ} {g : GateSpec} (hi : g.i < M) (hj : g.j < M) :keyCode M g < 3 * M * M := byunfold keyCodehave hop : g.op.idx ≤ 2 := by cases g.op <;> simp [SLPOp.idx]have h1 : g.i * M + g.j < M * M := bycalcg.i * M + g.j < g.i * M + M := Nat.add_lt_add_left hj __ = (g.i + 1) * M := by ring_ ≤ M * M := Nat.mul_le_mul_right M hihave h2 : g.op.idx * M * M ≤ 2 * M * M :=Nat.mul_le_mul_right M (Nat.mul_le_mul_right M hop)calcg.op.idx * M * M + g.i * M + g.j = g.op.idx * M * M + (g.i * M + g.j) := by ring_ < 2 * M * M + M * M := Nat.add_lt_add_of_le_of_lt h2 h1_ = 3 * M * M := by ringprivate lemma keyCode_lt_iff {M : ℕ} {g₁ g₂ : GateSpec}(hi₁ : g₁.i < M) (hj₁ : g₁.j < M) (hi₂ : g₂.i < M) (hj₂ : g₂.j < M) :keyCode M g₁ < keyCode M g₂ ↔ g₁.keyLt g₂ := byunfold keyCode GateSpec.keyLthave htail : ∀ a b : ℕ, a < M → b < M → a * M + b < M * M := fun a b ha hb => bycalca * M + b < a * M + M := Nat.add_lt_add_left hb __ = (a + 1) * M := by ring_ ≤ M * M := Nat.mul_le_mul_right M haconstructor· intro hby_cases hop : g₁.op.idx < g₂.op.idx· exact Or.inl hop· by_cases hop2 : g₂.op.idx < g₁.op.idx· exfalsohave h1 : g₂.op.idx * M * M + g₂.i * M + g₂.j < (g₂.op.idx + 1) * M * M := bycalcg₂.op.idx * M * M + g₂.i * M + g₂.j = g₂.op.idx * M * M + (g₂.i * M + g₂.j) := by ring_ < g₂.op.idx * M * M + M * M := Nat.add_lt_add_left (htail _ _ hi₂ hj₂) __ = (g₂.op.idx + 1) * M * M := by ringhave h2 : (g₂.op.idx + 1) * M * M ≤ g₁.op.idx * M * M :=Nat.mul_le_mul_right M (Nat.mul_le_mul_right M hop2)omega· have hop_eq : g₁.op.idx = g₂.op.idx := by omegaright; refine ⟨hop_eq, ?_⟩rw [hop_eq] at hhave h' : g₁.i * M + g₁.j < g₂.i * M + g₂.j := by omegaby_cases hi : g₁.i < g₂.i· exact Or.inl hi· by_cases hi2 : g₂.i < g₁.i· exfalsohave h1 : g₂.i * M + g₂.j < (g₂.i + 1) * M := bycalcg₂.i * M + g₂.j < g₂.i * M + M := Nat.add_lt_add_left hj₂ __ = (g₂.i + 1) * M := by ringhave h2 : (g₂.i + 1) * M ≤ g₁.i * M := Nat.mul_le_mul_right M hi2omega· have hi_eq : g₁.i = g₂.i := by omegarw [hi_eq] at h'right; exact ⟨hi_eq, by omega⟩· intro hrcases h with hop | ⟨hop, hi | ⟨hi, hj⟩⟩· have h1 : g₁.op.idx * M * M + g₁.i * M + g₁.j < (g₁.op.idx + 1) * M * M := bycalcg₁.op.idx * M * M + g₁.i * M + g₁.j = g₁.op.idx * M * M + (g₁.i * M + g₁.j) := by ring_ < g₁.op.idx * M * M + M * M := Nat.add_lt_add_left (htail _ _ hi₁ hj₁) __ = (g₁.op.idx + 1) * M * M := by ringhave h2 : (g₁.op.idx + 1) * M * M ≤ g₂.op.idx * M * M :=Nat.mul_le_mul_right M (Nat.mul_le_mul_right M hop)omega· rw [hop]have h1 : g₁.i * M + g₁.j < (g₁.i + 1) * M := bycalcg₁.i * M + g₁.j < g₁.i * M + M := Nat.add_lt_add_left hj₁ __ = (g₁.i + 1) * M := by ringhave h2 : (g₁.i + 1) * M ≤ g₂.i * M := Nat.mul_le_mul_right M hiomega· rw [hop, hi]; omegaprivate def lexWeightAux (B M : ℕ) : List GateSpec → ℕ| [] => 0| g :: rest => keyCode M g * B ^ rest.length + lexWeightAux B M restprivate lemma lexWeightAux_lt {B M : ℕ} (hB : 0 < B) :∀ (l : List GateSpec), (∀ g ∈ l, keyCode M g < B) → lexWeightAux B M l < B ^ l.length| [], _ => by simp [lexWeightAux]| g :: rest, h => bysimp only [lexWeightAux, List.length_cons, pow_succ']have hg : keyCode M g < B := h g (by simp)have hrest := lexWeightAux_lt hB rest (fun x hx => h x (by simp [hx]))have hpow : 0 < B ^ rest.length := pow_pos hB _calckeyCode M g * B ^ rest.length + lexWeightAux B M rest< keyCode M g * B ^ rest.length + B ^ rest.length := Nat.add_lt_add_left hrest __ = (keyCode M g + 1) * B ^ rest.length := by ring_ ≤ B * B ^ rest.length := Nat.mul_le_mul_right _ hgprivate lemma lexWeightAux_lt_of_prefix {B M : ℕ} (hB : 0 < B) :∀ (l₁ l₂ : List GateSpec) (p : ℕ)(hlen : l₁.length = l₂.length) (hp : p < l₁.length),(∀ g ∈ l₂, keyCode M g < B) →(∀ idx (h1 : idx < p), l₂[idx]'(by omega) = l₁[idx]'(by omega)) →keyCode M (l₂[p]'(by omega)) < keyCode M (l₁[p]'(by omega)) →lexWeightAux B M l₂ < lexWeightAux B M l₁| [], _, _, _, hp, _, _, _ => by simp at hp| _ :: _, [], _, hlen, _, _, _, _ => by simp at hlen| g₁ :: r₁, g₂ :: r₂, 0, hlen, _, hbound, _, hlt => bysimp only [List.length_cons, Nat.add_right_cancel_iff] at hlensimp only [List.getElem_cons_zero] at hltsimp only [lexWeightAux, ← hlen]have hrest := lexWeightAux_lt hB r₂ (fun x hx => hbound x (by simp [hx]))rw [← hlen] at hrestcalckeyCode M g₂ * B ^ r₁.length + lexWeightAux B M r₂< keyCode M g₂ * B ^ r₁.length + B ^ r₁.length := Nat.add_lt_add_left hrest __ = (keyCode M g₂ + 1) * B ^ r₁.length := by ring_ ≤ keyCode M g₁ * B ^ r₁.length := Nat.mul_le_mul_right _ hlt_ ≤ keyCode M g₁ * B ^ r₁.length + lexWeightAux B M r₁ := Nat.le_add_right _ _| g₁ :: r₁, g₂ :: r₂, p + 1, hlen, hp, hbound, hpref, hlt => byhave hg : g₂ = g₁ := hpref 0 (by omega)subst hgsimp only [lexWeightAux]have hlen' : r₁.length = r₂.length := by simp at hlen; omegarw [hlen']refine Nat.add_lt_add_left (lexWeightAux_lt_of_prefix hB r₁ r₂ p hlen' (by simp at hp; omega)(fun x hx => hbound x (by simp [hx])) ?_ ?_) _· intro idx hidxexact hpref (idx + 1) (by omega)· exact hltprivate def lexWeight (n : ℕ) (gs : List GateSpec) : ℕ :=lexWeightAux (3 * (n + 2) * (n + 2)) (n + 2) gs/-! ## 4. Main Theorem: `exists_canonical` -//-- Minimal well-formed lists computing `±f` satisfy `UsedGates`. -/private lemma minimal_used {f : Polynomial ℤ} {n : ℕ}(hmin : ∀ gs' : List GateSpec, WellFormed gs' → gs'.length < n → ¬ ComputesSigned f gs'){gs : List GateSpec} (hwf : WellFormed gs) (hlen : gs.length = n) (hcomp : ComputesSigned f gs) :UsedGates gs := byintro k hkby_contra hdeadpush Not at hdeadhave hdead' : ∀ (k' : ℕ) (hk' : k' < gs.length), k < k' → gs[k'].i ≠ k + 2 ∧ gs[k'].j ≠ k + 2 :=fun k' hk' hkk' => hdead k' hk' hkk'have hwf' := deleteUnused_wellFormed hwf hdead'have hlen' : (deleteUnused gs k).length < n := by rw [deleteUnused_length]; omegahave hout := deleteUnused_output hwf hk hdead'have hcomp' : ComputesSigned f (deleteUnused gs k) := by simpa [ComputesSigned, hout] using hcompexact hmin (deleteUnused gs k) hwf' hlen' hcomp'/-- Minimal well-formed lists computing `±f` (with `f ∉ {1, -1, X, -X}`) satisfy `NodupWires`. -/private lemma minimal_nodup {f : Polynomial ℤ}(hf1 : f ≠ 1) (hf1' : f ≠ -1) (hfX : f ≠ Polynomial.X) (hfX' : f ≠ -Polynomial.X){n : ℕ}(hmin : ∀ gs' : List GateSpec, WellFormed gs' → gs'.length < n → ¬ ComputesSigned f gs'){gs : List GateSpec} (hwf : WellFormed gs) (hlen : gs.length = n) (hcomp : ComputesSigned f gs) :NodupWires gs := byintro k hk m hmsuffices h : ∀ flip : Bool, (wireVals gs).getD (k + 2) 0 ≠ sgnVal flip * (wireVals gs).getD m 0 byexact ⟨by simpa [sgnVal] using h false, by simpa [sgnVal] using h true⟩intro flip hdupby_cases hlast : k + 1 = gs.length· have hout : output gs = (wireVals gs).getD (k + 2) 0 := byhave h1 : gs.length + 1 = k + 2 := by omegasimp [output, h1]rw [← hout] at hduprcases m with _ | _ | m'· rw [wireVals_zero] at hduprcases hcomp with hpos | hneg <;> cases flip <;> simp [sgnVal] at hdup· exact hf1 (hpos.symm.trans hdup)· exact hf1' (hpos.symm.trans hdup)· exact hf1' (neg_eq_iff_eq_neg.mp (hneg.symm.trans hdup))· exact hf1 (neg_inj.mp (hneg.symm.trans hdup))· rw [wireVals_one] at hduprcases hcomp with hpos | hneg <;> cases flip <;> simp [sgnVal] at hdup· exact hfX (hpos.symm.trans hdup)· exact hfX' (hpos.symm.trans hdup)· exact hfX' (neg_eq_iff_eq_neg.mp (hneg.symm.trans hdup))· exact hfX (neg_inj.mp (hneg.symm.trans hdup))· have hm_lt : m' + 1 < gs.length := by omegalet gs' := gs.take (m' + 1)have hlen' : gs'.length = m' + 1 := by simp [gs', hm_lt.le]have hwf' : WellFormed gs' := byintro r hrhave hr1 : r < m' + 1 := by simpa [hlen'] using hrhave hr_gs : r < gs.length := by omegahave hget : gs'[r] = gs[r] := by simp [gs']rw [hget]exact hwf r hr_gshave hout' : output gs' = (wireVals gs).getD (m' + 2) 0 := byhave htk := wireVals_take_getD gs hm_lt.le (w := m' + 2) (by omega)simpa [output, gs', hlen'] using htkhave hcomp' : ComputesSigned f gs' := byrw [ComputesSigned, hout']rcases hcomp with hpos | hneg <;> cases flip <;> simp [sgnVal] at hdup· left; exact hdup.symm.trans hpos· right; exact neg_eq_iff_eq_neg.mp (hdup.symm.trans hpos)· right; exact hdup.symm.trans hneg· left; exact neg_inj.mp (hdup.symm.trans hneg)exact hmin gs' hwf' (by omega) hcomp'· have hk1 : k + 1 < gs.length := by omegahave hwf' := redirGate_wellFormed hwf hm fliphave hcomp' := redirGate_computesSigned hwf hcomp hk1 hm flip hduphave hlen' : (redirGate gs k m flip).length < n := by rw [redirGate_length]; omegaexact hmin _ hwf' hlen' hcomp'/-- Any `UsedGates` + `NodupWires` list with nonzero output has `NonzeroWires`. -/private lemma nonzeroWires_of_used_nodup {gs : List GateSpec}(hwf : WellFormed gs) (hused : UsedGates gs) (hnodup : NodupWires gs)(hout : output gs ≠ 0) :NonzeroWires gs := byclassicalby_contra hnzsimp only [NonzeroWires, not_forall, not_not] at hnzlet S : Finset ℕ := (Finset.range gs.length).filter (fun k => (wireVals gs).getD (k + 2) 0 = 0)have hS_ne : S.Nonempty := byrcases hnz with ⟨k, hk, hk0⟩exact ⟨k, Finset.mem_filter.mpr ⟨Finset.mem_range.mpr hk, hk0⟩⟩let k := S.max' hS_nehave hk_mem : k ∈ S := Finset.max'_mem S hS_nehave hk_lt : k < gs.length := Finset.mem_range.mp (Finset.mem_filter.mp hk_mem).1have hk_zero : (wireVals gs).getD (k + 2) 0 = 0 := (Finset.mem_filter.mp hk_mem).2have hk_not_last : k + 1 < gs.length := byby_contra hgehave hlast : k + 1 = gs.length := by omegahave hout_eq : output gs = (wireVals gs).getD (k + 2) 0 := byhave h1 : gs.length + 1 = k + 2 := by omegasimp [output, h1]exact hout (hout_eq.trans hk_zero)rcases hused k hk_not_last with ⟨k', hk', hkk', hor⟩have hk'_ne : (wireVals gs).getD (k' + 2) 0 ≠ 0 := byintro h0have hmem : k' ∈ S := Finset.mem_filter.mpr ⟨Finset.mem_range.mpr hk', h0⟩have hle := Finset.le_max' S k' hmemomegahave hgate := wireVals_gate_wf hwf hk'have hgi := (hwf k' hk').1have hgj := (hwf k' hk').2cases hop : gs[k'].op <;> simp only [hop, SLPOp.applyPoly] at hgate· rcases hor with hi | hj· rw [hi, hk_zero, zero_add] at hgateexact (hnodup k' hk' gs[k'].j hgj).1 hgate· rw [hj, hk_zero, add_zero] at hgateexact (hnodup k' hk' gs[k'].i hgi).1 hgate· rcases hor with hi | hj· rw [hi, hk_zero, zero_sub] at hgateexact (hnodup k' hk' gs[k'].j hgj).2 hgate· rw [hj, hk_zero, sub_zero] at hgateexact (hnodup k' hk' gs[k'].i hgi).1 hgate· rcases hor with hi | hj· rw [hi, hk_zero, zero_mul] at hgateexact hk'_ne hgate· rw [hj, hk_zero, mul_zero] at hgateexact hk'_ne hgate/-- **Main Canonicalization Soundness Theorem (`exists_canonical`):**For every `t` and `P : SLP t` with nonzero output `f := P.evalPoly ≠ 0`,either `f ∈ {1, -1, X, -X}` or there exists a `Canonical` gate list `gs` with`1 ≤ gs.length ≤ t` computing `f` or `-f`. -/theorem exists_canonical {t : ℕ} (P : SLP t) (hf : P.evalPoly ≠ 0) :(P.evalPoly = 1 ∨ P.evalPoly = -1 ∨ P.evalPoly = Polynomial.X ∨ P.evalPoly = -Polynomial.X) ∨∃ gs : List GateSpec, Canonical gs ∧ 1 ≤ gs.length ∧ gs.length ≤ t ∧(output gs = P.evalPoly ∨ output gs = -P.evalPoly) := byclassicalset f := P.evalPolyby_cases hbase : f = 1 ∨ f = -1 ∨ f = Polynomial.X ∨ f = -Polynomial.X· exact Or.inl hbaserightpush Not at hbasercases hbase with ⟨hf1, hf1', hfX, hfX'⟩have hex_len : ∃ n : ℕ, ∃ gs : List GateSpec, WellFormed gs ∧ gs.length = n ∧ ComputesSigned f gs :=⟨t, P.toGateList, P.toGateList_wellFormed, P.toGateList_length, Or.inl P.output_toGateList⟩let n := Nat.find hex_lenhave hn_spec : ∃ gs : List GateSpec, WellFormed gs ∧ gs.length = n ∧ ComputesSigned f gs :=Nat.find_spec hex_lenhave hn_le : n ≤ t := Nat.find_min' hex_len ⟨P.toGateList, P.toGateList_wellFormed,P.toGateList_length, Or.inl P.output_toGateList⟩have hn_min : ∀ gs' : List GateSpec, WellFormed gs' → gs'.length < n → ¬ ComputesSigned f gs' := byintro gs' hwf' hlt' hcomp'exact Nat.find_min hex_len hlt' ⟨gs', hwf', rfl, hcomp'⟩have hn_pos : 1 ≤ n := byby_contra h0have hn0 : n = 0 := by omegarcases hn_spec with ⟨gs, _, hlen, hcomp⟩have hnil : gs = [] := List.eq_nil_of_length_eq_zero (hlen.trans hn0)subst hnilhave hout : output [] = Polynomial.X := by simp [output, wireVals, wireValsAux]rcases hcomp with hpos | hneg· exact hfX (hpos.symm.trans hout)· exact hfX' (neg_eq_iff_eq_neg.mp (hneg.symm.trans hout))-- Take one minimal-length witness and normalize it to get a GoodNormalized witnessrcases hn_spec with ⟨gs₁, hwf₁, hlen₁, hcomp₁⟩have hused₁ := minimal_used hn_min hwf₁ hlen₁ hcomp₁have hnodup₁ := minimal_nodup hf1 hf1' hfX hfX' hn_min hwf₁ hlen₁ hcomp₁have hout₁ : output gs₁ ≠ 0 := byrcases hcomp₁ with h | h <;> rw [h]· exact hf· exact neg_ne_zero.mpr hfhave hnz₁ := nonzeroWires_of_used_nodup hwf₁ hused₁ hnodup₁ hout₁let gs₂ := ordNormalize gs₁have hwf₂ := ordNormalize_wellFormed hwf₁have hlen₂ : gs₂.length = n := by simp [gs₂, ordNormalize_length, hlen₁]have hord₂ := (ordNormalize_wireVals_and_ord hwf₁ hnz₁).2have hnz₂ := ordNormalize_preserves_nonzero hwf₁ hnz₁have hnodup₂ := ordNormalize_preserves_nodup hwf₁ hnz₁ hnodup₁have hused₂ := ordNormalize_preserves_used hused₁have hcomp₂ := ordNormalize_computesSigned hwf₁ hnz₁ hcomp₁-- Minimize lexWeight among all GoodNormalized lists of length nlet GoodNorm (gs : List GateSpec) : Prop :=WellFormed gs ∧ gs.length = n ∧ OrdCanonical gs ∧ NonzeroWires gs ∧NodupWires gs ∧ UsedGates gs ∧ ComputesSigned f gshave hex_w : ∃ w : ℕ, ∃ gs : List GateSpec, GoodNorm gs ∧ lexWeight n gs = w :=⟨lexWeight n gs₂, gs₂, ⟨hwf₂, hlen₂, hord₂, hnz₂, hnodup₂, hused₂, hcomp₂⟩, rfl⟩let w_min := Nat.find hex_wrcases Nat.find_spec hex_w with ⟨gs, ⟨hwf, hlen, hord, hnz, hnodup, hused, hcomp⟩, hw_eq⟩have hlex : LexOrdered gs := byintro k hk1 hk2 h1 h2 hind_i hind_jby_contra hnotrw [GateSpec.not_keyLe_iff] at hnot-- Swap gates k-1 and k, then re-normalizelet gs_sw := swapRaw gs khave hwf_sw := swapRaw_wellFormed hwf hk1 hk2 hind_i hind_jhave hnz_sw := swapRaw_preserves_nonzero hwf hnz hk1 hk2 hind_i hind_jhave hnodup_sw := swapRaw_preserves_nodup hwf hnodup hk1 hk2 hind_i hind_jhave hused_sw := swapRaw_preserves_used hused hk1 hk2 hind_i hind_jhave hcomp_sw := swapRaw_computesSigned hwf hcomp hk1 hk2 hind_i hind_jhave hord_pref := swapRaw_ord_prefix hord hk1 hk2let gs' := ordNormalize gs_swhave hwf' := ordNormalize_wellFormed hwf_swhave hlen' : gs'.length = n := bydsimp only [gs', gs_sw]rw [ordNormalize_length, swapRaw_length, hlen]have hord' := (ordNormalize_wireVals_and_ord hwf_sw hnz_sw).2have hnz' := ordNormalize_preserves_nonzero hwf_sw hnz_swhave hnodup' := ordNormalize_preserves_nodup hwf_sw hnz_sw hnodup_swhave hused' := ordNormalize_preserves_used hused_swhave hcomp' := ordNormalize_computesSigned hwf_sw hnz_sw hcomp_sw-- Compare lexWeight n gs' < lexWeight n gshave hB : 0 < 3 * (n + 2) * (n + 2) := by positivityhave hbound : ∀ g ∈ gs', keyCode (n + 2) g < 3 * (n + 2) * (n + 2) := byintro g hgrcases List.mem_iff_getElem.mp hg with ⟨m, hm, rfl⟩have hgm : gs'[m].i < m + 2 ∧ gs'[m].j < m + 2 := hwf' m hmrw [hlen'] at hmexact keyCode_lt (by omega) (by omega)have hpref_eq : ∀ idx (hidx : idx < k - 1),gs'[idx]'(by omega) = gs[idx]'(by omega) := byintro idx hidxhave hnorm_eq := ordNormalize_prefix_eq hwf_sw (p := k + 1)(by rw [swapRaw_length]; omega) hord_pref idx (by omega)rw [hnorm_eq]simp [swapRaw, show idx ≠ k - 1 by omega, show idx ≠ k by omega, hidx]have hpk_eq : gs'[k - 1]'(by omega) = gs[k]'(by omega) := byhave hnorm_eq := ordNormalize_prefix_eq hwf_sw (p := k + 1)(by rw [swapRaw_length]; omega) hord_pref (k - 1) (by omega)rw [hnorm_eq]simp [swapRaw, show k < gs.length by omega]have hlt_code : keyCode (n + 2) (gs'[k - 1]'(by omega)) <keyCode (n + 2) (gs[k - 1]'(by omega)) := byrw [hpk_eq]have hgk := hwf k (by omega)have hgk1 := hwf (k - 1) (by omega)rw [keyCode_lt_iff (by omega) (by omega) (by omega) (by omega)]exact hnothave hw_lt : lexWeight n gs' < lexWeight n gs :=lexWeightAux_lt_of_prefix hB gs gs' (k - 1) (by omega) (by omega) hbound hpref_eq hlt_codeexact Nat.find_min hex_w (hw_eq ▸ hw_lt)⟨gs', ⟨hwf', hlen', hord', hnz', hnodup', hused', hcomp'⟩, rfl⟩exact ⟨gs, ⟨hwf, hord, hnz, hnodup, hused, hlex⟩, by omega, by omega, hcomp⟩/-! ## 5. Dead-Gate Pruning Bound (`deadgate_count_bound`) -//-- Set of gate wires among `{2, ..., d + 1}` that are not an operand of any of thefirst `d` gates `0, ..., d - 1`. This matches `unused_mask` in the enumerator after `d` gates. -/def unusedWires (gs : List GateSpec) (d : ℕ) : Finset ℕ :=(Finset.Ico 2 (d + 2)).filter (fun w =>∀ k < d, (gs.getD k default).i ≠ w ∧ (gs.getD k default).j ≠ w)theorem unusedWires_zero (gs : List GateSpec) : unusedWires gs 0 = ∅ := bysimp [unusedWires]theorem unusedWires_succ {gs : List GateSpec} (hwf : WellFormed gs) {d : ℕ} (hd : d < gs.length) :unusedWires gs (d + 1) =insert (d + 2) (unusedWires gs d \ {gs[d].i, gs[d].j}) := byext wsimp only [unusedWires, Finset.mem_insert, Finset.mem_sdiff, Finset.mem_filter,Finset.mem_Ico, Finset.mem_singleton]constructor· rintro ⟨⟨hw2, hwd3⟩, hnot⟩by_cases hweq : w = d + 2· exact Or.inl hweq· rightrefine ⟨⟨⟨hw2, by omega⟩, fun k hk => hnot k (by omega)⟩, ?_⟩have hd_get := hnot d (by omega)rw [getD_eq_getElem_of_lt _ _ hd] at hd_gettauto· rintro (rfl | ⟨⟨⟨hw2, hwd2⟩, hnot⟩, hne⟩)· refine ⟨⟨by omega, by omega⟩, fun k hk => ?_⟩have hk_gs : k < gs.length := by omegahave hgk := hwf k hk_gsrw [getD_eq_getElem_of_lt _ _ hk_gs]omega· refine ⟨⟨hw2, by omega⟩, fun k hk => ?_⟩by_cases hkd : k < d· exact hnot k hkd· have heq : k = d := by omegasubst heqrw [getD_eq_getElem_of_lt _ _ hd]tauto/-- **Dead-Gate Pruning Soundness (`deadgate_count_bound`):**For any gate list of length `n` satisfying `UsedGates` (in particular, any `Canonical` list)and any prefix length `d < n`, the number of unused gate wires after `d` gates is at most`n - d + 1`. Equivalently, with `depth = d - 1` and `rem_after = n - 1 - depth`,`unused_cnt ≤ rem_after + 1`. -/theorem deadgate_count_bound {gs : List GateSpec} (hused : UsedGates gs){d : ℕ} (hd : d < gs.length) :(unusedWires gs d).card ≤ gs.length - d + 1 := byclassicallet n := gs.lengthlet A : Finset ℕ := unusedWires gs dlet B : Finset ℕ := Finset.Ico (d + 2) (n + 1)let Slots : Finset ℕ := (Finset.Ico d n).biUnion (fun k' =>({(gs.getD k' default).i, (gs.getD k' default).j} : Finset ℕ))have hdisj : Disjoint A B := byrw [Finset.disjoint_left]intro w hwA hwBhave h1 := (Finset.mem_Ico.mp (Finset.mem_filter.mp hwA).1).2have h2 := (Finset.mem_Ico.mp hwB).1omegahave hA_sub : A ⊆ Slots := byintro w hwAhave hw_ico := (Finset.mem_filter.mp hwA).1have hnot := (Finset.mem_filter.mp hwA).2have hw2 : 2 ≤ w := (Finset.mem_Ico.mp hw_ico).1have hwd : w < d + 2 := (Finset.mem_Ico.mp hw_ico).2have hu : w - 2 + 1 < n := by omegarcases hused (w - 2) hu with ⟨k', hk', huk', hor⟩have hdk' : d ≤ k' := byby_contra hlthave hk'_d : k' < d := by omegahave hnd := hnot k' hk'_drw [getD_eq_getElem_of_lt _ _ hk'] at hndomegarw [Finset.mem_biUnion]refine ⟨k', Finset.mem_Ico.mpr ⟨hdk', hk'⟩, ?_⟩rw [getD_eq_getElem_of_lt _ _ hk', Finset.mem_insert, Finset.mem_singleton]omegahave hB_sub : B ⊆ Slots := byintro w hwBhave hw1 : d + 2 ≤ w := (Finset.mem_Ico.mp hwB).1have hw2 : w < n + 1 := (Finset.mem_Ico.mp hwB).2have hu : w - 2 + 1 < n := by omegarcases hused (w - 2) hu with ⟨k', hk', huk', hor⟩have hdk' : d ≤ k' := by omegarw [Finset.mem_biUnion]refine ⟨k', Finset.mem_Ico.mpr ⟨hdk', hk'⟩, ?_⟩rw [getD_eq_getElem_of_lt _ _ hk', Finset.mem_insert, Finset.mem_singleton]omegahave hAB_sub : A ∪ B ⊆ Slots := Finset.union_subset hA_sub hB_subhave hSlots_card : Slots.card ≤ 2 * (n - d) := bycalcSlots.card ≤ ∑ k' ∈ Finset.Ico d n,({(gs.getD k' default).i, (gs.getD k' default).j} : Finset ℕ).card :=Finset.card_biUnion_le_ ≤ ∑ _k' ∈ Finset.Ico d n, 2 :=Finset.sum_le_sum (fun _ _ => Finset.card_le_two)_ = (Finset.Ico d n).card * 2 := Finset.sum_const_nat (fun _ _ => rfl)_ = 2 * (n - d) := by rw [Nat.card_Ico]; ringhave hB_card : B.card = n - d - 1 := byrw [Nat.card_Ico]omegahave hAB_card : A.card + B.card ≤ 2 * (n - d) := bycalcA.card + B.card = (A ∪ B).card := (Finset.card_union_of_disjoint hdisj).symm_ ≤ Slots.card := Finset.card_le_card hAB_sub_ ≤ 2 * (n - d) := hSlots_carddsimp only [A, n] at hAB_card hB_cardomega/-- Corollary for `Canonical` lists. -/theorem deadgate_count_bound_of_canonical {gs : List GateSpec} (hcan : Canonical gs){d : ℕ} (hd : d < gs.length) :(unusedWires gs d).card ≤ gs.length - d + 1 :=deadgate_count_bound hcan.used hd/-- Leaf-level consequence of `UsedGates`: before the last gate (`1 ≤ gs.length`),at most `2` gate wires remain unused, and every unused gate wire must be an operandof the last gate `gs[gs.length - 1]`. -/theorem unusedWires_last_gate {gs : List GateSpec} (hused : UsedGates gs)(hne : 1 ≤ gs.length) :(unusedWires gs (gs.length - 1)).card ≤ 2 ∧∀ w ∈ unusedWires gs (gs.length - 1),w = (gs[gs.length - 1]'(by omega)).i ∨ w = (gs[gs.length - 1]'(by omega)).j := byhave hcard : (unusedWires gs (gs.length - 1)).card ≤ 2 := byhave h := deadgate_count_bound hused (d := gs.length - 1) (by omega)omegarefine ⟨hcard, fun w hw => ?_⟩have hw_ico := (Finset.mem_filter.mp hw).1have hnot := (Finset.mem_filter.mp hw).2have hw2 : 2 ≤ w := (Finset.mem_Ico.mp hw_ico).1have hwd : w < gs.length - 1 + 2 := (Finset.mem_Ico.mp hw_ico).2rcases hused (w - 2) (by omega) with ⟨k', hk', huk', hor⟩have hk'_ge : gs.length - 1 ≤ k' := byby_contra hlthave hnd := hnot k' (by omega)rw [getD_eq_getElem_of_lt _ _ hk'] at hndomegahave hk'_eq : k' = gs.length - 1 := by omegasubst hk'_eqrw [show w - 2 + 2 = w by omega] at horexact hor.imp Eq.symm Eq.symm/-! ## 6. Checklist Reduction Theorem (`zmax_le_of_checklist`) -//-- Negating a polynomial in `ℤ[X]` preserves its distinct integer root count. -/theorem intRootCount_neg (f : Polynomial ℤ) : intRootCount (-f) = intRootCount f := bysimp [intRootCount, intRootSet]/-- The basic seed polynomials `{1, -1, X, -X}` each have at most `1` distinct integer root. -/theorem intRootCount_le_one_of_basic {f : Polynomial ℤ}(hf : f = 1 ∨ f = -1 ∨ f = Polynomial.X ∨ f = -Polynomial.X) :intRootCount f ≤ 1 := byrcases hf with rfl | rfl | rfl | rfl· exact (intRootCount_le_natDegree one_ne_zero).trans (by simp)· rw [intRootCount_neg]exact (intRootCount_le_natDegree one_ne_zero).trans (by simp)· exact (intRootCount_le_natDegree Polynomial.X_ne_zero).trans (by simp)· rw [intRootCount_neg]exact (intRootCount_le_natDegree Polynomial.X_ne_zero).trans (by simp)/-- **Checklist Soundness Theorem (`zmax_le_of_checklist`):**If every `Canonical` gate list `gs` with `1 ≤ gs.length ≤ τ` and `output gs ≠ 0`satisfies `intRootCount (output gs) ≤ K` (where `1 ≤ K`), then every nonzero `SLP t`with `t ≤ τ` computes a polynomial with at most `K` distinct integer roots. -/theorem zmax_le_of_checklist (τ K : ℕ) (hK : 1 ≤ K)(hcheck : ∀ gs : List GateSpec, Canonical gs → 1 ≤ gs.length → gs.length ≤ τ →output gs ≠ 0 → intRootCount (output gs) ≤ K) :∀ t ≤ τ, ∀ P : SLP t, P.evalPoly ≠ 0 → intRootCount P.evalPoly ≤ K := byintro t ht P hnercases exists_canonical P hne with hbasic | ⟨gs, hcan, h1, hlen_t, hout⟩· exact (intRootCount_le_one_of_basic hbasic).trans hK· have hlen_tau : gs.length ≤ τ := hlen_t.trans hthave hout_ne : output gs ≠ 0 := byrcases hout with h | h <;> rw [h]· exact hne· exact neg_ne_zero.mpr hnehave hbound := hcheck gs hcan h1 hlen_tau hout_nercases hout with h | h· rwa [← h]· rwa [← intRootCount_neg P.evalPoly, ← h]/-- **Conditional Upper Bound `z_max(9) ≤ 6`:**If the exhaustive checklist over all `Canonical` gate lists of length `1 ≤ n ≤ 9`with nonzero output establishes `intRootCount (output gs) ≤ 6`, then every nonzero`SLP t` with `t ≤ 9` has at most `6` distinct integer roots.*Verification boundary:* This theorem machine-checks the soundness of canonicalization(`WellFormed`, `OrdCanonical`, `NonzeroWires`, `NodupWires`, `UsedGates`, `LexOrdered`)and sign/length reduction. It does **not** internally verify the C/Python enumeration loop,hash-table collision freeness, or the execution trace of external runs; those must besupplied via the checklist hypothesis `hcheck` (or per-leaf certificates). -/theorem zmax9_le_six_of_checklist(hcheck : ∀ gs : List GateSpec, Canonical gs → 1 ≤ gs.length → gs.length ≤ 9 →output gs ≠ 0 → intRootCount (output gs) ≤ 6) :∀ t ≤ 9, ∀ P : SLP t, P.evalPoly ≠ 0 → intRootCount P.evalPoly ≤ 6 :=zmax_le_of_checklist 9 6 (by omega) hcheck/-- **Conditional Upper Bound `z_max(10) ≤ 7`:**If the exhaustive checklist over all `Canonical` gate lists of length `1 ≤ n ≤ 10`with nonzero output establishes `intRootCount (output gs) ≤ 7`, then every nonzero`SLP t` with `t ≤ 10` has at most `7` distinct integer roots.*Verification boundary:* Same as `zmax9_le_six_of_checklist`; the external enumerator loopitself is not verified inside Lean and appears as the hypothesis `hcheck`. -/theorem zmax10_le_seven_of_checklist(hcheck : ∀ gs : List GateSpec, Canonical gs → 1 ≤ gs.length → gs.length ≤ 10 →output gs ≠ 0 → intRootCount (output gs) ≤ 7) :∀ t ≤ 10, ∀ P : SLP t, P.evalPoly ≠ 0 → intRootCount P.evalPoly ≤ 7 :=zmax_le_of_checklist 10 7 (by omega) hcheckend Research.PvsNP.Tauend