FormalRV

PauliRotation 674 declarations in 47 modules

FormalRV.PauliRotation.Compiler.CircuitCompile

FormalRV/PauliRotation/Compiler/CircuitCompile.lean
FormalRV.PauliRotation.Compiler.CircuitCompile ───────────────────────────────────── The TOP of the pipeline: logical Clifford+T/Toffoli circuits → naive gate-by-gate rotation sequence (the standard dictionary, `Compile.lean`) → VERIFIED ASAP parallelization (`Scheduler.lean`): compileScheduled gs = scheduleList (compileNaive gs) with the end-to-end theorem `compileScheduled_denote`: the parallelized layers denote EXACTLY the naive sequence (side condition: every emitted axis canonical and in width — DECIDABLE, so concrete circuits discharge it by `decide`). HONESTY: this verifies the OPTIMIZER leg (reorder/parallelize preserves semantics, counts preserved on the nose). The DICTIONARY leg (the naive sequence denotes the gate matrices, up to global phase) is the known open item (`README.md` gap 2); until it lands, `seqDenote (compileNaive gs)` is the specification the schedule provably meets.
inductiveLGate
inductive LGate
A logical circuit gate (Clifford + T + Toffoli-class). Multi-qubit gates expect distinct operands; `CCZ`/`CCX` expect `a < b < c` (canonical operand order).
defLGate.compile
def LGate.compile : LGate → List Rot
  | .X q        => (xGate q).flatten
  | .Y q        => (yGate q).flatten
  | .Z q        => (zGate q).flatten
  | .H q        => (hGate q).flatten
  | .S q        => (sGate q).flatten
  | .Sdg q      => (sDag q).flatten
  | .T q        => (tGate q).flatten
  | .Tdg q      => (tDag q).flatten
  | .CNOT c t   => (cnotGate c t).flatten
  | .CCZ a b c  => (cczGate a b c).flatten
  | .CCX a b c  => (hGate c).flatten ++ (cczGate a b c).flatten ++ (hGate c).flatten
Naive per-gate compilation: the standard dictionary, serialized.
defcompileNaive
def compileNaive (gs : List LGate) : List Rot
Naive circuit compilation: gate by gate, in sequence.
defcompileScheduled
def compileScheduled (gs : List LGate) : RotProg
*The compiled-and-parallelized program.**
theoremcompileScheduled_denote
theorem compileScheduled_denote (n : Nat) (gs : List LGate)
    (h : ∀ r ∈ compileNaive gs,
          sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n) :
    RotProg.denote n (compileScheduled gs) = seqDenote n (compileNaive gs)
*END-TO-END OPTIMIZER CORRECTNESS**: the parallel layers denote exactly the naive gate-by-gate sequence. The side condition (canonical axes, in width) is decidable — concrete circuits discharge it by `decide`.
theoremcompileScheduled_countPi8
theorem compileScheduled_countPi8 (gs : List LGate) :
    countPi8 (compileScheduled gs)
      = (compileNaive gs).countP (fun r => r.angle == RAngle.piEighth)
The T-count of the schedule is the T-count of the naive sequence — parallelization never creates or destroys non-Clifford content.
theoremcompileScheduled_depth_le
theorem compileScheduled_depth_le (gs : List LGate) :
    rotDepth (compileScheduled gs) ≤ (compileNaive gs).length
Depth never exceeds the sequential rotation count.
defdemoCircuit
def demoCircuit : List LGate
example(example)
example : ∀ r ∈ compileNaive demoCircuit,
    sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ 2
example(example)
example : (compileNaive demoCircuit).length = 5
example(example)
example : rotDepth (compileScheduled demoCircuit) = 2
example(example)
example : countPi8 (compileScheduled demoCircuit) = 2
example(example)
example : RotProg.wf (compileScheduled demoCircuit) = true
example(example)
example : (compileNaive [.CCX 0 1 2]).length = 13
example(example)
example : rotDepth (compileScheduled [.CCX 0 1 2]) = 5
example(example)
example : countPi8 (compileScheduled [.CCX 0 1 2]) = 7
example(example)
example : rotDepth (compileScheduled [.CCX 0 1 2, .CCX 3 4 5]) = 5
example(example)
example : countPi8 (compileScheduled [.CCX 0 1 2, .CCX 3 4 5]) = 14

FormalRV.PauliRotation.Compiler.GateBridge

FormalRV/PauliRotation/Compiler/GateBridge.lean
FormalRV.PauliRotation.Compiler.GateBridge ───────────────────────────────── THE ARITHMETIC ENTRY POINT: compile the reversible Gate IR (`FormalRV.Framework.Gate` — I/X/CX/CCX/seq, the language of EVERY arithmetic gadget: Cuccaro, Gidney, ModularAdder, ModMult, ModExp, Windowed, …) into the Pauli-rotation IR. Toffoli-class circuits are EXACTLY Clifford+T, so this compilation is exact — no approximation. X q ↦ X_q^{π/2} (1 rotation) CX c t ↦ the signed-π/4 triple (`cnotGate`) (3 rotations) CCX a b t ↦ H_t ; CCZ(sort₃ a b t) ; H_t (13 rotations, 7 of them π/8 — CCZ is symmetric, so operands sort) Generic theorems — EVERY Gate-IR gadget inherits them by composition with its existing `tcount`/`countToffoli` theorems: • `gateRots_countPi8` : rotation T-count = `Gate.tcount` ON THE NOSE • `gateRots_length` : #rotations = countX + 3·countCNOT + 13·countToffoli • `gateRots_bounded` : every emitted axis canonical, within `Resource.width g` (needs distinct operands) • `gateRotSchedule_denote` : the ASAP-parallelized program denotes exactly the naive sequence • `gateRotSchedule_countPi8` : … and scheduling keeps the T-count. HONESTY: the correctness theorem is semantic preservation of the compile+schedule pipeline against `seqDenote (gateRots g)`; the dictionary leg (`seqDenote (gateRots g)` = the Gate's unitary, up to global phase) is the known open item (`README.md`).
defsort3
def sort3 (a b c : Nat) : Nat × Nat × Nat
Ascending ordering of three indices (CCZ is symmetric in its qubits).
defgateRots
def gateRots : Gate → List Rot
  | .I          => []
  | .X q        => [⟨false, .piHalf, [⟨q, .x⟩]⟩]
  | .CX c t     => (cnotGate c t).flatten
  | .CCX a b t  =>
      (hGate t).flatten
        ++ (cczGate (sort3 a b t).1 (sort3 a b t).2.1 (sort3 a b t).2.2).flatten
        ++ (hGate t).flatten
  | .seq g h    => gateRots g ++ gateRots h
*Gate-IR → rotation sequence** (naive, gate by gate; exact).
defgateRotSchedule
def gateRotSchedule (g : Gate) : RotProg
*The compiled-and-parallelized gadget.**
defopsOK
def opsOK : Gate → Bool
  | .I          => true
  | .X _        => true
  | .CX c t     => decide (c ≠ t)
  | .CCX a b t  => decide (a ≠ b) && decide (a ≠ t) && decide (b ≠ t)
  | .seq g h    => opsOK g && opsOK h
Distinct operands (the Gate-IR well-formedness this compilation needs).
theoremgateRots_countPi8
theorem gateRots_countPi8 (g : Gate) :
    (gateRots g).countP (fun r => r.angle == RAngle.piEighth) = Gate.tcount g
*Rotation-level T-count = `Gate.tcount`, on the nose** — every gadget's existing T-count theorem becomes its rotation T-count theorem for free.
theoremgateRots_length
theorem gateRots_length (g : Gate) :
    (gateRots g).length
      = countX g + 3 * countCNOT g + 13 * countToffoli g
Total rotation count, in terms of the INDEPENDENT `Resource/` walkers.
theoremhGate_bounded
private theorem hGate_bounded (q : Nat) :
    ∀ r ∈ (hGate q).flatten,
      sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ q + 1
theoremcnotGate_bounded
private theorem cnotGate_bounded (c t : Nat) (h : c ≠ t) :
    ∀ r ∈ (cnotGate c t).flatten,
      sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ max (c + 1) (t + 1)
theoremcczGate_bounded
private theorem cczGate_bounded (x y z : Nat) (hxy : x < y) (hyz : y < z) :
    ∀ r ∈ (cczGate x y z).flatten,
      sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ z + 1
theoremsort3_spec
theorem sort3_spec (a b t : Nat) (hab : a ≠ b) (hat : a ≠ t)
    (hbt : b ≠ t) :
    (sort3 a b t).1 < (sort3 a b t).2.1
      ∧ (sort3 a b t).2.1 < (sort3 a b t).2.2
      ∧ (sort3 a b t).2.2 + 1 ≤ max (max (a + 1) (b + 1)) (t + 1)
theoremgateRots_bounded
theorem gateRots_bounded (g : Gate) (hops : opsOK g = true) :
    ∀ r ∈ gateRots g,
      sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ width g
Every emitted rotation has a canonical axis within the gate's width.
theoremgateRotSchedule_denote
theorem gateRotSchedule_denote (n : Nat) (g : Gate)
    (hops : opsOK g = true) (hw : width g ≤ n) :
    RotProg.denote n (gateRotSchedule g) = seqDenote n (gateRots g)
*GADGET CORRECTNESS (optimizer leg)**: for any well-operand Gate-IR gadget within width `n`, the ASAP-parallelized rotation program denotes EXACTLY the naive gate-by-gate rotation sequence.
theoremgateRotSchedule_countPi8
theorem gateRotSchedule_countPi8 (g : Gate) :
    countPi8 (gateRotSchedule g) = Gate.tcount g
*GADGET T-COUNT**: the parallelized program's π/8 count IS the gadget's `Gate.tcount` — compose with any existing per-gadget `tcount` theorem.
theoremgateRotSchedule_depth_le
theorem gateRotSchedule_depth_le (g : Gate) :
    rotDepth (gateRotSchedule g) ≤ (gateRots g).length
Scheduling also preserves the total rotation budget.
example(example)
example :  -- a MAJ-style fragment: CX;CX;CCX = 3+3+13 rotations, 7 of them T
    (gateRots (.seq (.CX 2 1) (.seq (.CX 2 0) (.CCX 0 1 2)))).length = 19
example(example)
example :
    countPi8 (gateRotSchedule (.seq (.CX 2 1) (.seq (.CX 2 0) (.CCX 0 1 2)))) = 7
example(example)
example :  -- operands distinct, fits in 3 qubits: the semantic theorem applies
    opsOK (.seq (.CX 2 1) (.seq (.CX 2 0) (.CCX 0 1 2))) = true
      ∧ width (.seq (.CX 2 1) (.seq (.CX 2 0) (.CCX 0 1 2))) ≤ 3
example(example)
example :  -- CCX with operands in ANY order compiles (CCZ symmetric, sort₃)
    countPi8 (gateRotSchedule (.CCX 5 2 4)) = 7

FormalRV.PauliRotation.Compiler.GateDictionary

FormalRV/PauliRotation/Compiler/GateDictionary.lean
FormalRV.PauliRotation.Compiler.GateDictionary ────────────────────────────── The STANDARD gate dictionary into the Pauli-rotation IR (Litinski Table 1, full-angle convention `P_θ = e^{-iθP}`, each up to an explicit global phase): T = Z_{π/8} T† = Z_{−π/8} S = Z_{π/4} S† = Z_{−π/4} Z = Z_{π/2} X = X_{π/2} Y = Y_{π/2} (phase −i each) H = Z_{π/4} · X_{π/4} · Z_{π/4} (phase e^{−iπ/4}) CNOT(c,t) = (Z_c X_t)_{π/4} · (Z_c)_{−π/4} · (X_t)_{−π/4} (phase e^{iπ/4}) CCZ(a,b,c) = the SEVEN π/8 rotations of the phase polynomial 4·xyz = x+y+z − x⊕y − x⊕z − y⊕z + x⊕y⊕z : +π/8 on each single Z, −π/8 on each pair ZZ, +π/8 on the triple ZZZ — `countPi8 = 7` (seven T's, cf. `PPM/Rules/EightTToCCZScheme.lean`). These are concrete syntax trees: well-formedness and the resource counts below close by `decide`, and a skeptic can `#eval` the counters directly. HONESTY BOUNDARY: this file defines the dictionary and proves its STRUCTURAL properties (wf, counts, depth). The matrix-correctness leg (each program's `RotProg.denote` equals the gate matrix up to the stated global phase) is the designated next step over `Semantics.lean` (`rotOf_pi_div_two` already gives the Pauli rows); the CCZ sign orientation will additionally be discharged against the proven net-phase data in `PPM/Rules/EightTToCCZScheme.lean`. Until that leg lands, do NOT cite this dictionary as verified semantics.
defrot1
def rot1 (neg : Bool) (a : RAngle) (k : PKind) (q : Nat) : RotProg
One single-axis rotation as a one-layer program.
deftGate
def tGate (q : Nat) : RotProg
deftDag
def tDag  (q : Nat) : RotProg
defsGate
def sGate (q : Nat) : RotProg
defsDag
def sDag  (q : Nat) : RotProg
defzGate
def zGate (q : Nat) : RotProg
defxGate
def xGate (q : Nat) : RotProg
defyGate
def yGate (q : Nat) : RotProg
defhGate
def hGate (q : Nat) : RotProg
`H = Z_{π/4} · X_{π/4} · Z_{π/4}` (up to the global phase `e^{−iπ/4}`).
defmk2
def mk2 (c : Nat) (kc : PKind) (t : Nat) (kt : PKind) : PauliProduct
The sorted two-qubit product with kind `kc` on `c` and `kt` on `t` (canonical whatever the index order; `c ≠ t` expected).
defcnotGate
def cnotGate (c t : Nat) : RotProg
`CNOT(c,t) = (Z_c X_t)_{π/4} · (Z_c)_{−π/4} · (X_t)_{−π/4}` (up to the global phase `e^{iπ/4}`). Note the NEGATIVE quarter rotations — this is why the IR carries signs.
defcczGate
def cczGate (a b c : Nat) : RotProg
`CCZ(a,b,c)` for `a < b < c`: `+π/8` on the three single `Z`s, `−π/8` on the three pairs, `+π/8` on the triple. Seven non-Clifford rotations and NOTHING else — the rotation IR shows the Toffoli-class T-count directly.
defcczLayer
def cczLayer (a b c : Nat) : RotProg
All seven CCZ axes are Z-type, hence pairwise commuting: the WHOLE CCZ phase polynomial is ONE parallel layer. This is the parallelism the layer structure exists to express.
example(example)
example : RotProg.wf (tGate 3) = true
example(example)
example : RotProg.wf (hGate 0) = true
example(example)
example : RotProg.wf (cnotGate 0 1) = true
example(example)
example : RotProg.wf (cnotGate 5 2) = true
example(example)
example : RotProg.wf (cczGate 0 1 2) = true
example(example)
example : RotProg.wf (cczLayer 0 1 2) = true
example(example)
example : countPi8 (tGate 0) = 1
example(example)
example : countPi8 (hGate 0) = 0
example(example)
example : countPi8 (cnotGate 0 1) = 0
example(example)
example : countPi8 (cczGate 0 1 2) = 7
example(example)
example : rotDepth (cczGate 0 1 2) = 7
example(example)
example : rotDepth (cczLayer 0 1 2) = 1
example(example)
example : countPi8 (cczLayer 0 1 2) = 7

FormalRV.PauliRotation.Compiler.Optimizer

FormalRV/PauliRotation/Compiler/Optimizer.lean
FormalRV.PauliRotation.Compiler.Optimizer ──────────────────────────────── *THE CERTIFICATE-CHECKED OPTIMIZER INTERFACE.** An optimizer — heuristic, hand-written, or EXTERNAL AND UNTRUSTED — does not need to be verified. It needs to EMIT A TRACE: a list of rule applications, each naming a position in the flat rotation sequence. The executable checker `applyTrace` replays the trace, re-checking every side condition (commutation, angle class, canonicity), and ONE soundness theorem says the replay preserves the sequence's denotation EXACTLY: applyTrace n t rs = some rs' → seqDenote n rs = seqDenote n rs' The rule set is complete for Litinski reorganization: swap — exchange adjacent rotations with commuting axes push — DELAY a ±π/4 Clifford past an anticommuting rotation (axis ↦ `mulF`, sign in `neg` — `Rot.pushedBy`) pushHalf — delay a ±π/2 Pauli rotation (angle sign flips) cancel — adjacent inverse rotations vanish merge — adjacent equal rotations fuse to the doubled angle mergePi — two adjacent equal π rotations vanish ((−1)² = 1) All checks are decidable and the boundedness invariant (canonical axes within width) is PRESERVED by every rule (`mulF_sorted`/`mulF_width` cover the push), so traces compose. Schedule the checked output with `scheduleList` (or the K-bounded `scheduleListK`) and the existing capstones carry optimized programs end-to-end.
defrotsBoundedB
def rotsBoundedB (n : Nat) (rs : List Rot) : Bool
Every axis canonical and within width `n`.
theoremrotsBoundedB_cons
theorem rotsBoundedB_cons {n : Nat} {r : Rot} {rs : List Rot}
    (h : rotsBoundedB n (r :: rs) = true) :
    (sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n)
      ∧ rotsBoundedB n rs = true
theoremrotsBoundedB_cons_intro
theorem rotsBoundedB_cons_intro {n : Nat} {r : Rot} {rs : List Rot}
    (hr : sortedStrict r.axis = true) (hw : PauliProduct.width r.axis ≤ n)
    (h : rotsBoundedB n rs = true) : rotsBoundedB n (r :: rs) = true
inductiveRuleApp
inductive RuleApp
One optimizer rule, naming the position it fires at.
defapplyHead
def applyHead : RuleApp → List Rot → Option (List Rot)
  | .swap _, r :: s :: rest =>
      if commF s.axis r.axis then some (s :: r :: rest) else none
  | .push _, r :: s :: rest =>
      if r.angle == .piQuarter && !(commF r.axis s.axis)
      then some (r.pushedBy s :: r :: rest) else none
  | .pushHalf _, r :: s :: rest =>
      if r.angle == .piHalf && !(commF r.axis s.axis)
      then some (Rot.pushedByHalf s :: r :: rest) else none
  | .cancel _, r :: s :: rest =>
      if s == r.inv then some rest else none
  | .merge _, r :: s :: rest =>
Apply one rule at the HEAD of the sequence (all side conditions re-checked).
defapplyRule
def applyRule (a : RuleApp) : List Rot → Option (List Rot)
Apply a rule at its named position.
defapplyTrace
def applyTrace : List RuleApp → List Rot → Option (List Rot)
  | [], rs => some rs
  | a :: t, rs => (applyRule a rs).bind (applyTrace t)
*The executable certificate checker**: replay a trace.
theoremdenote_merge_rot
private theorem denote_merge_rot (n : Nat) (r : Rot) {b : RAngle}
    (hb : r.angle.doubled = some b) :
    Rot.denote n r * Rot.denote n r
      = Rot.denote n { r with angle
Merging two equal rotations at the `Rot` level.
theoremrotOf_two_pi
private theorem rotOf_two_pi {d : Type*} [DecidableEq d]
    (M : Matrix d d ℂ) : rotOf (2 * Real.pi) M = 1
theoremrotOf_neg_two_pi
private theorem rotOf_neg_two_pi {d : Type*} [DecidableEq d]
    (M : Matrix d d ℂ) : rotOf (-(2 * Real.pi)) M = 1
theoremdenote_merge_pi
private theorem denote_merge_pi (n : Nat) (r : Rot) (hr : r.angle = .pi) :
    Rot.denote n r * Rot.denote n r = 1
Two equal π rotations vanish at the `Rot` level.
theoremapplyHead_sound
theorem applyHead_sound (n : Nat) (a : RuleApp) (rs rs' : List Rot)
    (hb : rotsBoundedB n rs = true)
    (h : applyHead a rs = some rs') :
    seqDenote n rs = seqDenote n rs' ∧ rotsBoundedB n rs' = true
*Head-rule soundness + invariant preservation.**
theoremapplyRule_go_sound
theorem applyRule_go_sound (n : Nat) (a : RuleApp) :
    ∀ (k : Nat) (rs rs' : List Rot),
      rotsBoundedB n rs = true →
      applyRule.go a k rs = some rs' →
      seqDenote n rs = seqDenote n rs' ∧ rotsBoundedB n rs' = true
  | 0, rs, rs', hb, h => applyHead_sound n a rs rs' hb h
  | k + 1, r :: rs, rs', hb, h =>
theoremapplyRule_sound
theorem applyRule_sound (n : Nat) (a : RuleApp) (rs rs' : List Rot)
    (hb : rotsBoundedB n rs = true)
    (h : applyRule a rs = some rs') :
    seqDenote n rs = seqDenote n rs' ∧ rotsBoundedB n rs' = true
*One-rule soundness**: a successful application preserves the denotation exactly and keeps the sequence bounded.
theoremapplyTrace_sound
theorem applyTrace_sound (n : Nat) :
    ∀ (t : List RuleApp) (rs rs' : List Rot),
      rotsBoundedB n rs = true →
      applyTrace t rs = some rs' →
      seqDenote n rs = seqDenote n rs' ∧ rotsBoundedB n rs' = true
  | [], rs, rs', hb, h =>
*THE CERTIFICATE THEOREM**: replaying ANY accepted trace preserves the flat sequence's denotation EXACTLY (and boundedness). An optimizer needs no verification — only a trace the checker accepts.
theoremgateRots_boundedB
theorem gateRots_boundedB (g : FormalRV.Framework.Gate) (n : Nat)
    (hops : opsOK g = true) (hw : Resource.width g ≤ n) :
    rotsBoundedB n (gateRots g) = true
Boundedness of the compiled gadget sequence (discharges the checker's input invariant from `gateRots_bounded`).
theoremoptimized_schedule_applyNat
theorem optimized_schedule_applyNat (n : Nat) (g : FormalRV.Framework.Gate)
    (hops : opsOK g = true) (hw : Resource.width g ≤ n)
    (t : List RuleApp) (rs' : List Rot)
    (hcheck : applyTrace t (gateRots g) = some rs') :
    RotProg.denote n (scheduleList rs')
      = gphase g • applyMat n g
*THE OPTIMIZED-COMPILATION CAPSTONE**: take ANY gadget, optimize its rotation sequence with ANY untrusted optimizer, check the trace, schedule the result — the layered program still implements the gadget's Boolean semantics up to its global phase.
theoremoptimized_scheduleK_applyNat
theorem optimized_scheduleK_applyNat (K n : Nat) (hK : 1 ≤ K)
    (g : FormalRV.Framework.Gate)
    (hops : opsOK g = true) (hw : Resource.width g ≤ n)
    (t : List RuleApp) (rs' : List Rot)
    (hcheck : applyTrace t (gateRots g) = some rs') :
    RotProg.denote n (scheduleListK K rs') = gphase g • applyMat n g
      ∧ layersLE K (scheduleListK K rs') = true
*THE HARDWARE-BOUNDED OPTIMIZED CAPSTONE**: certified-optimize ANY gadget's rotation sequence, compile it with the K-bounded scheduler — the layered program respects the hardware cap (every layer ≤ K) AND still implements the gadget's Boolean semantics up to its global phase.

FormalRV.PauliRotation.Compiler.PushRules

FormalRV/PauliRotation/Compiler/PushRules.lean
FormalRV.PauliRotation.Compiler.PushRules ──────────────────────────────── *VERIFIED CLIFFORD PUSHING — the Litinski optimization, syntactically.** "A Game of Surface Codes" delays every Clifford (±π/4, ±π/2) rotation past the non-Clifford content to the end of the circuit. The matrix-level push rule (`rot_quarter_push`, CircuitIdentities) conjugates axes as MATRICES; this file makes the move a verified rewrite on the rotation IR: [r] :: [s] :: p ≡ [r.pushedBy s] :: [r] :: p (r a ±π/4 rotation, axes anticommuting) where `(r.pushedBy s).axis = mulF r.axis s.axis` and the ±i of the phase-tracked product (`axisMat_mulF`, PauliPhase) lands in the `neg` flag. Counts are preserved ON THE NOSE (the pushed rotation keeps its angle — Clifford pushing NEVER changes the T-count), and so is depth. §1 matrix-level chirality twins (`rot_quarter_push_neg`, `rot_half_push`/`_neg`, `rotOf_neg_axis`); §2 the syntactic pushed rotation and its `theta` bookkeeping; §3 the Rot-level DELAY theorems (quarter, both chiralities; half); §4 program-level adjacent rewrites + count/depth preservation (swap for commuting axes, push for anticommuting).
theoremrotOf_neg_axis
theorem rotOf_neg_axis (θ : ℝ) (M : Matrix m m ℂ) :
    rotOf θ (-M) = rotOf (-θ) M
Negating the axis negates the angle.
theoremrot_quarter_push_neg
theorem rot_quarter_push_neg {M N : Matrix m m ℂ} (hM : M * M = 1)
    (hMN : M * N = -(N * M)) (φ : ℝ) :
    rotOf (-(Real.pi / 4)) M * rotOf φ N
      = rotOf φ (Complex.I • (M * N)) * rotOf (-(Real.pi / 4)) M
The −π/4 chirality of the push rule: the conjugated axis is `(+i)·MN`.
theoremrot_half_push
theorem rot_half_push {M N : Matrix m m ℂ}
    (hMN : M * N = -(N * M)) (φ : ℝ) :
    rotOf φ N * rotOf (Real.pi / 2) M
      = rotOf (Real.pi / 2) M * rotOf (-φ) N
*The π/2 delay rule**: a π/2 (Pauli) rotation delays past an anticommuting rotation by flipping its angle sign — already in DELAY form (`s` first on the left = `s` earlier in the program).
theoremrot_half_push_neg
theorem rot_half_push_neg {M N : Matrix m m ℂ}
    (hMN : M * N = -(N * M)) (φ : ℝ) :
    rotOf φ N * rotOf (-(Real.pi / 2)) M
      = rotOf (-(Real.pi / 2)) M * rotOf (-φ) N
The −π/2 chirality (identical conjugation — the scalars cancel).
defRot.pushedBy
def Rot.pushedBy (r s : Rot) : Rot
`s` as it must appear EARLIER in the program when the ±π/4 Clifford `r` is DELAYED past it: the axis becomes the frame product `mulF r.axis s.axis` and the ±i of the phase-tracked product lands in `neg`.
defRot.pushedByHalf
def Rot.pushedByHalf (s : Rot) : Rot
`s` as it must appear earlier when a ±π/2 (Pauli) rotation is delayed past it: same axis, angle sign flipped.
theoremtheta_xor_true
private theorem theta_xor_true (ne : Bool) (a : RAngle)
    (ax ax' : PauliProduct) :
    Rot.theta ⟨ne ^^ true, a, ax'⟩ = -(Rot.theta ⟨ne, a, ax⟩)
theoremtheta_xor_false
private theorem theta_xor_false (ne : Bool) (a : RAngle)
    (ax ax' : PauliProduct) :
    Rot.theta ⟨ne ^^ false, a, ax'⟩ = Rot.theta ⟨ne, a, ax⟩
theoremaxisMat_anticomm_of_not_commF
theorem axisMat_anticomm_of_not_commF (n : Nat) {P Q : PauliProduct}
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (h : commF P Q = false) :
    axisMat n P * axisMat n Q = -(axisMat n Q * axisMat n P)
Anticommutation of the axis matrices from `commF = false`.
theoremRot.denote_push_delay
theorem Rot.denote_push_delay (n : Nat) (r s : Rot)
    (hr : r.angle = .piQuarter)
    (hsr : sortedStrict r.axis = true)
    (hwr : PauliProduct.width r.axis ≤ n)
    (hss : sortedStrict s.axis = true)
    (hac : commF r.axis s.axis = false) :
    Rot.denote n s * Rot.denote n r
      = Rot.denote n r * Rot.denote n (r.pushedBy s)
*THE QUARTER-PUSH DELAY THEOREM**: a ±π/4 rotation `r` delays past an anticommuting rotation `s` (any angle), with `s` replaced by the SYNTACTIC `r.pushedBy s` — axis `mulF r.axis s.axis`, sign in `neg`.
theoremRot.denote_push_half_delay
theorem Rot.denote_push_half_delay (n : Nat) (r s : Rot)
    (hr : r.angle = .piHalf)
    (hsr : sortedStrict r.axis = true)
    (hwr : PauliProduct.width r.axis ≤ n)
    (hac : commF r.axis s.axis = false) :
    Rot.denote n s * Rot.denote n r
      = Rot.denote n r * Rot.denote n (Rot.pushedByHalf s)
*THE HALF-PUSH DELAY THEOREM**: a ±π/2 (Pauli) rotation delays past an anticommuting rotation by flipping its angle sign — axis untouched.
theoremlayer_singleton
private theorem layer_singleton (n : Nat) (x : Rot) :
    RotLayer.denote n [x] = Rot.denote n x
theoremdenote_push_adjacent
theorem denote_push_adjacent (n : Nat) (r s : Rot) (p : RotProg)
    (hr : r.angle = .piQuarter)
    (hsr : sortedStrict r.axis = true)
    (hwr : PauliProduct.width r.axis ≤ n)
    (hss : sortedStrict s.axis = true)
    (hac : commF r.axis s.axis = false) :
    RotProg.denote n ([r] :: [s] :: p)
      = RotProg.denote n ([r.pushedBy s] :: [r] :: p)
*THE PUSH REWRITE**: delay an adjacent ±π/4 Clifford past an anticommuting rotation.
theoremdenote_push_half_adjacent
theorem denote_push_half_adjacent (n : Nat) (r s : Rot) (p : RotProg)
    (hr : r.angle = .piHalf)
    (hsr : sortedStrict r.axis = true)
    (hwr : PauliProduct.width r.axis ≤ n)
    (hac : commF r.axis s.axis = false) :
    RotProg.denote n ([r] :: [s] :: p)
      = RotProg.denote n ([Rot.pushedByHalf s] :: [r] :: p)
*THE HALF-PUSH REWRITE**: delay an adjacent ±π/2 Pauli rotation.
theoremdenote_swap_adjacent
theorem denote_swap_adjacent (n : Nat) (r s : Rot) (p : RotProg)
    (hss : sortedStrict s.axis = true)
    (hws : PauliProduct.width s.axis ≤ n)
    (hc : commF s.axis r.axis = true) :
    RotProg.denote n ([r] :: [s] :: p)
      = RotProg.denote n ([s] :: [r] :: p)
*THE SWAP REWRITE**: adjacent rotations with commuting axes exchange.
theoremcountAngle_push_adjacent
theorem countAngle_push_adjacent (a : RAngle) (r s : Rot) (p : RotProg) :
    countAngle a ([r.pushedBy s] :: [r] :: p)
      = countAngle a ([r] :: [s] :: p)
theoremcountPi8_push_adjacent
theorem countPi8_push_adjacent (r s : Rot) (p : RotProg) :
    countPi8 ([r.pushedBy s] :: [r] :: p) = countPi8 ([r] :: [s] :: p)
*Clifford pushing preserves the T-count on the nose.**
theoremcountRot_push_adjacent
theorem countRot_push_adjacent (r s : Rot) (p : RotProg) :
    countRot ([r.pushedBy s] :: [r] :: p) = countRot ([r] :: [s] :: p)
theoremrotDepth_push_adjacent
theorem rotDepth_push_adjacent (r s : Rot) (p : RotProg) :
    rotDepth ([r.pushedBy s] :: [r] :: p) = rotDepth ([r] :: [s] :: p)
example(example)
example :
    (Rot.pushedBy ⟨false, .piQuarter, [⟨0, .z⟩]⟩
        ⟨false, .piEighth, [⟨0, .x⟩]⟩)
      = ⟨true, .piEighth, [⟨0, .y⟩]⟩
Delaying S(Z₀) past X₀(π/8): the pushed axis is `Z·X = iY` — the rotation becomes a `−Y` rotation (phase `i`, flip).
example(example)
example :
    (Rot.pushedBy ⟨false, .piQuarter, [⟨0, .z⟩]⟩
        ⟨false, .piEighth, [⟨0, .y⟩]⟩)
      = ⟨false, .piEighth, [⟨0, .x⟩]⟩
Delaying S(Z₀) past Y₀: `Z·Y = −iX` — no flip.
example(example)
example :
    (Rot.pushedBy ⟨false, .piQuarter, [⟨0, .z⟩, ⟨1, .z⟩]⟩
        ⟨false, .piEighth, [⟨0, .x⟩]⟩)
      = ⟨true, .piEighth, [⟨0, .y⟩, ⟨1, .z⟩]⟩
Delaying S(Z₀Z₁) past X₀(π/8): pushed axis `Y₀Z₁`.

FormalRV.PauliRotation.Compiler.QFTLadder

FormalRV/PauliRotation/Compiler/QFTLadder.lean
FormalRV.PauliRotation.Compiler.QFTLadder ──────────────────────────────── QFT / QPE in the rotation IR — the HONEST boundary. The inverse-QFT ladder rotation at distance `m = j − t` is `controlled_Rz j t (−π/2^m)`, whose constituent single-qubit rotations have full angle `π/2^(m+2)`: exactly Clifford+T iff `m ≤ 1` — the SAME boundary the repo's actual Clifford+T compiler proves (`QFT/AQFTCompile.lean: compileLadder_isCliffordT`, cutoff ≤ 2), with the dropped `m ≥ 2` tail carrying the DERIVED approximation budget (`compileLadder_error_budget`). So what compiles EXACTLY into the four-angle rotation IR is the banded (cutoff-2) inverse QFT: • each kept ladder gate (m = 1, the controlled-S† of adjacent pairs) is THREE Z-type π/8 rotations — all-Z, hence ONE commuting layer; • the Hadamards are the dictionary's three π/4 rotations; • the bit-reversal SWAPs are Clifford (9 π/4 rotations each). QPE then assembles as: H-layer ++ oracle (any Gate-IR modexp, via `GateBridge.gateRots` — exact) ++ banded inverse QFT, and its rotation T-count is `Gate.tcount oracle + 3·(k−1)` (`qpeSchedule_gate_countPi8`). HONESTY: (1) rotations with `m ≥ 2` are NOT expressible at the four discrete angles — they require Clifford+T synthesis; this file compiles the SAME banded circuit the proven error budget is about, never the exact QFT. (2) The correctness theorems here are the verified-optimizer leg (schedule = naive sequence); the dictionary leg (sequence = `uc_eval` of the BaseUCom circuit, up to global phase — including the CS† sign orientation) is the layer's known open item.
defcsDagRots
def csDagRots (t : Nat) : List Rot
The `m = 1` inverse-QFT ladder gate (controlled-S† on the adjacent pair `(t+1, t)`) as its three Z-type π/8 rotations — pairwise commuting, hence one parallel layer once scheduled.
defaqftLadderLow
def aqftLadderLow : Nat → List Rot
  | 0     => []
  | t + 1 => csDagRots t ++ (hGate t).flatten ++ aqftLadderLow t
Ladder for targets `t = k−1 … 0`: each keeps its adjacent CS† (control `t+1`) and ends with `H t`.
defswapRots
def swapRots (i j : Nat) : List Rot
A SWAP as three CNOTs (nine π/4 rotations — Clifford).
defbitRevRots
def bitRevRots (n : Nat) : List Rot
The bit-reversal cascade preceding the ladder.
defaqft2Rots
def aqft2Rots : Nat → List Rot
  | 0     => []
  | n + 1 => bitRevRots (n + 1) ++ ((hGate n).flatten ++ aqftLadderLow n)
*The banded inverse QFT, exactly in the rotation IR**: bit-reversal, the top target's `H`, then the kept ladder. (The dropped `m ≥ 2` rotations carry the existing derived error budget — see header.)
defaqft2Schedule
def aqft2Schedule (n : Nat) : RotProg
The parallelized banded inverse QFT.
theoremswapRots_countPi8
private theorem swapRots_countPi8 (i j : Nat) :
    (swapRots i j).countP (fun r => r.angle == RAngle.piEighth) = 0
theoremflatMap_countPi8_zero
private theorem flatMap_countPi8_zero (f : Nat → List Rot)
    (hf : ∀ i, (f i).countP (fun r => r.angle == RAngle.piEighth) = 0) :
    ∀ l : List Nat,
      (l.flatMap f).countP (fun r => r.angle == RAngle.piEighth) = 0
  | [] => rfl
  | i :: t =>
theorembitRevRots_countPi8
theorem bitRevRots_countPi8 (n : Nat) :
    (bitRevRots n).countP (fun r => r.angle == RAngle.piEighth) = 0
theoremaqftLadderLow_countPi8
theorem aqftLadderLow_countPi8 (t : Nat) :
    (aqftLadderLow t).countP (fun r => r.angle == RAngle.piEighth) = 3 * t
theoremaqft2Schedule_countPi8
theorem aqft2Schedule_countPi8 (n : Nat) :
    countPi8 (aqft2Schedule (n + 1)) = 3 * n
*The banded-IQFT T-count is `3·(k−1)`** (three T's per kept adjacent controlled-S†) — and scheduling preserves it on the nose.
theoremaqft2Schedule_denote
theorem aqft2Schedule_denote (W n : Nat)
    (h : ∀ r ∈ aqft2Rots n,
          sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ W) :
    RotProg.denote W (aqft2Schedule n) = seqDenote W (aqft2Rots n)
The optimizer leg for the banded IQFT (side condition decidable).
defhLayerRots
def hLayerRots (k : Nat) : List Rot
The QPE preparation layer: `H` on each of the `k` phase qubits.
defqpeRots
def qpeRots (k : Nat) (oracle : List Rot) : List Rot
*QPE in the rotation IR**, with the modular-exponentiation oracle given as ANY rotation sequence (e.g. `gateRots oracleGate` — exact, since the Gate-IR oracle is Toffoli-class).
defqpeSchedule
def qpeSchedule (k : Nat) (oracle : List Rot) : RotProg
The parallelized QPE program.
theoremhLayerRots_countPi8
theorem hLayerRots_countPi8 (k : Nat) :
    (hLayerRots k).countP (fun r => r.angle == RAngle.piEighth) = 0
theoremqpeSchedule_gate_countPi8
theorem qpeSchedule_gate_countPi8 (n : Nat) (g : Gate) :
    countPi8 (qpeSchedule (n + 1) (gateRots g)) = Gate.tcount g + 3 * n
*THE QPE T-COUNT**: oracle T-count plus `3·(k−1)` for the banded IQFT — stated against the INDEPENDENT Gate-IR counter, so every existing per-gadget `tcount` theorem instantiates it.
theoremqpeSchedule_denote
theorem qpeSchedule_denote (W k : Nat) (oracle : List Rot)
    (h : ∀ r ∈ qpeRots k oracle,
          sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ W) :
    RotProg.denote W (qpeSchedule k oracle) = seqDenote W (qpeRots k oracle)
The optimizer leg for assembled QPE (side condition decidable).
example(example)
example : (aqft2Rots 3).length = 24
example(example)
example : countPi8 (aqft2Schedule 3) = 6
example(example)
example : ∀ r ∈ aqft2Rots 3,
    sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ 3
example(example)
example : RotProg.wf (aqft2Schedule 3) = true
example(example)
example : countPi8 (qpeSchedule 2 (gateRots (.CCX 2 3 4))) = 10
example(example)
example : ∀ r ∈ qpeRots 2 (gateRots (.CCX 2 3 4)),
    sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ 5

FormalRV.PauliRotation.Compiler.Rules

FormalRV/PauliRotation/Compiler/Rules.lean
FormalRV.PauliRotation.Compiler.Rules ──────────────────────────── Optimization rules for Pauli-rotation programs, each carried by a SEMANTIC-PRESERVATION theorem over `Semantics.lean` and (where counts change) an honest COUNT theorem over `Resource/RotationCount.lean`: • `dropPi` — π rotations are global phases: removing them changes the denotation by exactly `(−1)^(countAngle .pi p)` (`dropPi_denote`), removes nothing else (`countAngle_dropPi`), and preserves well-formedness and depth. • cancellation — adjacent inverse rotations vanish (`denote_cancel_adjacent`), saving 2 rotations (`countRot_cancel_pair`). • angle merging — adjacent same-axis same-angle rotations fuse into the doubled angle (`denote_double_adjacent`): two T's = one S, two S's = one Pauli, …; a doubled π rotation vanishes outright (`denote_pi_sq_adjacent`). SCOPE: the rules below act on ADJACENT rotations (singleton layers). The commutation bridge they once waited on is PROVEN — CommBridge.lean (`axisMat_comm_of_commF`, `Rot.denote_swap`), Scheduler.lean lifts it to the verified ASAP parallelizer, and PushRules.lean adds the Litinski ANTICOMMUTING push (`denote_push_adjacent`, via the phase-tracked product `axisMat_mulF` of PauliPhase.lean). Nothing here assumes any of them; this file remains the adjacent-rule core.
defdropPiL
def dropPiL (L : RotLayer) : RotLayer
Remove the π rotations from a layer.
defdropPi
def dropPi (p : RotProg) : RotProg
Remove the π rotations from a program.
theoremdropPiL_denote
theorem dropPiL_denote (n : Nat) (L : RotLayer) :
    RotLayer.denote n L
      = ((-1 : ℂ) ^ countAngleL .pi L) • RotLayer.denote n (dropPiL L)
theoremdropPi_denote
theorem dropPi_denote (n : Nat) (p : RotProg) :
    RotProg.denote n p
      = ((-1 : ℂ) ^ countAngle .pi p) • RotProg.denote n (dropPi p)
*Soundness of `dropPi`**: removing π rotations changes the denotation by EXACTLY the global phase `(−1)^(number of π rotations)` — the exponent being the independent `Resource/` counter.
theoremcountAngleL_dropPiL
theorem countAngleL_dropPiL (a : RAngle) (ha : a ≠ .pi) (L : RotLayer) :
    countAngleL a (dropPiL L) = countAngleL a L
`dropPi` removes ONLY π rotations: every other angle's count is intact.
theoremcountAngle_dropPi
theorem countAngle_dropPi (a : RAngle) (ha : a ≠ .pi) (p : RotProg) :
    countAngle a (dropPi p) = countAngle a p
theoremcountPi8_dropPi
theorem countPi8_dropPi (p : RotProg) : countPi8 (dropPi p) = countPi8 p
In particular the T-count is untouched.
theoremdepth_dropPi
theorem depth_dropPi (p : RotProg) : rotDepth (dropPi p) = rotDepth p
`dropPi` does not change the parallel depth.
theoremall_filter_of_all
private theorem all_filter_of_all {α} (q f : α → Bool) (l : List α)
    (h : l.all f = true) : (l.filter q).all f = true
theoremlayerComm_filter
private theorem layerComm_filter (q : Rot → Bool) (L : RotLayer)
    (h : layerComm L = true) : layerComm (L.filter q) = true
theoremdropPiL_wf
theorem dropPiL_wf (L : RotLayer) (h : RotLayer.wf L = true) :
    RotLayer.wf (dropPiL L) = true
`dropPi` preserves layer well-formedness (a sub-multiset of a pairwise- commuting layer still pairwise commutes).
theoremdropPi_wf
theorem dropPi_wf (p : RotProg) (h : RotProg.wf p = true) :
    RotProg.wf (dropPi p) = true
theoremRot.denote_inv_mul
theorem Rot.denote_inv_mul (n : Nat) (r : Rot) :
    Rot.denote n r.inv * Rot.denote n r = 1
theoremdenote_cancel_adjacent
theorem denote_cancel_adjacent (n : Nat) (r : Rot) (p : RotProg) :
    RotProg.denote n ([r] :: [r.inv] :: p) = RotProg.denote n p
*The cancellation rule**: adjacent inverse rotations vanish.
theoremcountRot_cancel_pair
theorem countRot_cancel_pair (r : Rot) (p : RotProg) :
    countRot ([r] :: [r.inv] :: p) = countRot p + 2
The cancellation rule saves exactly two rotations …
theoremdepth_cancel_pair
theorem depth_cancel_pair (r : Rot) (p : RotProg) :
    rotDepth ([r] :: [r.inv] :: p) = rotDepth p + 2
… and two layers of depth.
defRAngle.doubled
def RAngle.doubled : RAngle → Option RAngle
  | .pi        => none
  | .piHalf    => some .pi
  | .piQuarter => some .piHalf
  | .piEighth  => some .piQuarter
Doubling an angle level (`none` for π: a doubled π rotation is `e^{-2πi} = 1`, i.e. it vanishes — see `denote_pi_sq_adjacent`).
theoremRAngle.doubled_val
theorem RAngle.doubled_val {a b : RAngle} (h : a.doubled = some b) :
    b.val = 2 * a.val
theoremdenote_double_adjacent
theorem denote_double_adjacent (n : Nat) (r : Rot) {b : RAngle}
    (hb : r.angle.doubled = some b) (p : RotProg) :
    RotProg.denote n ([r] :: [r] :: p)
      = RotProg.denote n ([{ r with angle
*The merge rule**: two adjacent equal rotations fuse into the doubled angle — two T's make an S, two S's make a Pauli, two Paulis make a π phase.
theoremdenote_pi_sq_adjacent
theorem denote_pi_sq_adjacent (n : Nat) (r : Rot) (h : r.angle = .pi)
    (p : RotProg) :
    RotProg.denote n ([r] :: [r] :: p) = RotProg.denote n p
A doubled π rotation vanishes outright (`(−1)² = 1`).
example(example)
example :  -- dropping a π rotation keeps the T-count
    countPi8 (dropPi [[⟨false, .pi, [⟨0, .z⟩]⟩], [⟨false, .piEighth, [⟨1, .z⟩]⟩]])
      = 1
example(example)
example :  -- two T's about Z[0] fuse into one S
    RAngle.doubled .piEighth = some .piQuarter

FormalRV.PauliRotation.Compiler.Scheduler

FormalRV/PauliRotation/Compiler/Scheduler.lean
FormalRV.PauliRotation.Compiler.Scheduler ──────────────────────────────── THE VERIFIED PARALLELIZER: greedy ASAP (as-soon-as-possible) scheduling of a rotation sequence into parallel layers, with full semantic preservation. ## The parallelism target (John's question 1) The optimum reachable by commutation alone is the CRITICAL PATH of the anticommutation DAG (nodes = rotations; edge `i → j` for `i < j` iff the axes anticommute): no valid layering can be shallower than the longest anticommuting chain, and greedy ASAP attains it — each rotation settles in the EARLIEST layer such that (a) it commutes with that whole layer and (b) it commutes with everything scheduled after it (so dragging it back is a chain of legal exchanges). ## The mechanical correctness recipe (John's question 2) One micro-lemma + one macro-lemma + induction — the standard verified- scheduler pattern (same shape as list-scheduling proofs in verified compilers): 1. EXCHANGE (`CommBridge.Rot.denote_swap`): adjacent rotations with syntactically commuting axes (`commF`) swap, semantics unchanged. 2. INSERTION (`insertASAP_denote`): if `r` commutes with everything after its landing spot, inserting it there equals appending it at the end — proved by lifting EXCHANGE through products (`Commute.list_prod_right`). 3. INDUCTION (`scheduleList_denote`): fold INSERTION over the input. Nothing here is semantically ad hoc: every step is the exchange lemma, applied through the algebra of `Commute`. Counters are preserved on the nose (`scheduleList_countAngle` — scheduling moves rotations, never makes or destroys them), well-formedness is preserved, and depth never exceeds the sequential length.
defpasses
def passes (r : Rot) (L : RotLayer) : Bool
`r` commutes with every rotation of the layer (syntactic test; guard orientation `commF s.axis r.axis` so the bridge applies with `s` canonical).
defpassesAll
def passesAll (r : Rot) (p : RotProg) : Bool
`r` commutes with every rotation of every layer.
definsertASAP
def insertASAP (r : Rot) : RotProg → RotProg
  | [] => [[r]]
  | L :: rest =>
      if passes r L && passesAll r rest
      then (L ++ [r]) :: rest
      else L :: insertASAP r rest
*ASAP insertion**: `r` settles in the first layer it commutes with, provided it also commutes with everything after (the legality of dragging it back); otherwise it walks right; if nothing accepts it, a fresh layer.
defscheduleList
def scheduleList (rs : List Rot) : RotProg
*The scheduler**: fold a rotation sequence (execution order) into parallel layers.
defseqDenote
noncomputable def seqDenote (n : Nat) : List Rot → Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
  | []      => 1
  | r :: rs => seqDenote n rs * Rot.denote n r
Sequential denotation of a rotation list (the naive gate-by-gate compilation's meaning; later rotations act on the left).
theoremdenote_singletons
theorem denote_singletons (n : Nat) (rs : List Rot) :
    RotProg.denote n (rs.map (fun r => [r])) = seqDenote n rs
A singleton-layer program means exactly the sequence.
defRotsBounded
def RotsBounded (n : Nat) (p : RotProg) : Prop
Per-rotation side conditions the bridge needs: canonical axis, in width.
theoremcommute_denote_layer
theorem commute_denote_layer (n : Nat) (r : Rot) (L : RotLayer)
    (hb : ∀ s ∈ L, sortedStrict s.axis = true ∧ PauliProduct.width s.axis ≤ n)
    (hp : passes r L = true) :
    Commute (Rot.denote n r) (RotLayer.denote n L)
theoremcommute_denote_prog
theorem commute_denote_prog (n : Nat) (r : Rot) (p : RotProg)
    (hb : RotsBounded n p) (hp : passesAll r p = true) :
    Commute (Rot.denote n r) (RotProg.denote n p)
theoreminsertASAP_denote
theorem insertASAP_denote (n : Nat) (r : Rot) (p : RotProg)
    (hb : RotsBounded n p) :
    RotProg.denote n (insertASAP r p) = Rot.denote n r * RotProg.denote n p
*Insertion is append, semantically**: wherever ASAP lands `r`, the program denotes exactly `⟦r⟧ · ⟦p⟧` — i.e. the same as running `p` then `r`.
theoreminsertASAP_bounded
theorem insertASAP_bounded (n : Nat) (r : Rot)
    (hr : sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n)
    (p : RotProg) (hb : RotsBounded n p) : RotsBounded n (insertASAP r p)
theoremscheduleList_denote_aux
private theorem scheduleList_denote_aux (n : Nat) (rs : List Rot) (acc : RotProg)
    (hrs : ∀ r ∈ rs, sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n)
    (hacc : RotsBounded n acc) :
    RotProg.denote n (rs.foldl (fun a r => insertASAP r a) acc)
      = seqDenote n rs * RotProg.denote n acc
theoremscheduleList_denote
theorem scheduleList_denote (n : Nat) (rs : List Rot)
    (hrs : ∀ r ∈ rs, sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n) :
    RotProg.denote n (scheduleList rs) = seqDenote n rs
*THE SCHEDULER CORRECTNESS THEOREM**: ASAP parallelization preserves the denotation exactly — for every rotation sequence (canonical axes, in width), the layered program means the same operator as the sequence.
theoreminsertASAP_countAngle
theorem insertASAP_countAngle (a : RAngle) (r : Rot) (p : RotProg) :
    countAngle a (insertASAP r p)
      = countAngle a p + (if r.angle == a then 1 else 0)
Scheduling never creates or destroys rotations: every angle count is preserved on the nose.
theoremscheduleList_countAngle
theorem scheduleList_countAngle (a : RAngle) (rs : List Rot) :
    countAngle a (scheduleList rs) = rs.countP (fun r => r.angle == a)
theoremscheduleList_countPi8
theorem scheduleList_countPi8 (rs : List Rot) :
    countPi8 (scheduleList rs) = rs.countP (fun r => r.angle == RAngle.piEighth)
In particular the T-count survives parallelization untouched.
theoreminsertASAP_depth_le
theorem insertASAP_depth_le (r : Rot) (p : RotProg) :
    rotDepth (insertASAP r p) ≤ rotDepth p + 1
Insertion adds at most one layer …
theoremscheduleList_depth_le
theorem scheduleList_depth_le (rs : List Rot) :
    rotDepth (scheduleList rs) ≤ rs.length
… so the parallel depth never exceeds the sequential length.
example(example)
example : scheduleList ((cczGate 0 1 2).flatten) = cczLayer 0 1 2
The serialized CCZ (depth 7) reschedules to EXACTLY the single parallel layer — the optimizer discovers `cczLayer` on its own.
example(example)
example : rotDepth (scheduleList ((cnotGate 0 1).flatten)) = 1
The serialized CNOT (depth 3) reschedules to one layer.
example(example)
example : rotDepth (scheduleList
    [⟨false, .piEighth, [⟨0, .x⟩]⟩, ⟨false, .piEighth, [⟨0, .z⟩]⟩]) = 2
Anticommuting rotations stay sequential — no false parallelism.
example(example)
example : rotDepth (scheduleList
    ((cczGate 0 1 2).flatten ++ (cczGate 3 4 5).flatten)) = 1
Two CCZs on disjoint triples: 14 rotations, depth 1.

FormalRV.PauliRotation.Compiler.SchedulerK

FormalRV/PauliRotation/Compiler/SchedulerK.lean
FormalRV.PauliRotation.Compiler.SchedulerK ───────────────────────────────── *THE HARDWARE-BOUNDED COMPILER: ≤ K joint Pauli rotations per layer.** Lattice-surgery hardware executes at most `K` joint Pauli measurements in parallel (QianXu-style: `K = 5`). `scheduleListK K` is the greedy ASAP parallelizer CONSTRAINED to layers of at most `K` rotations — a verified COMPILER from arbitrary rotation sequences to hardware-valid layered programs: • `scheduleListK_denote` — the layered program denotes EXACTLY the input sequence (matrix equality); • `scheduleListK_layers_le` — every layer has ≤ K rotations (validity against the hardware bound); • `scheduleListK_countAngle` — per-angle counts on the nose (T-count survives compilation); • `countRot_le_K_mul_depth` — THE UNIVERSAL LOWER BOUND: any K-valid program needs ≥ ⌈N/K⌉ layers; • `scheduleListK_depth_optimal_of_commuting` — for PAIRWISE-COMMUTING sequences (phase polynomials: CCZ/adder layers) the compiler ACHIEVES ⌈N/K⌉ — verified optimality, not heuristics. Correct-BY-CONSTRUCTION: unlike the certificate lane (Optimizer.lean), this compiler's output needs no per-run checking — one theorem covers every invocation.
definsertASAPK
def insertASAPK (K : Nat) (r : Rot) : RotProg → RotProg
  | [] => [[r]]
  | L :: rest =>
      if decide (L.length < K) && passes r L && passesAll r rest
      then (L ++ [r]) :: rest
      else L :: insertASAPK K r rest
ASAP insertion with the hardware cap: a layer accepts only if it has ROOM (`< K`) and `r` commutes with it and with everything after.
defscheduleListK
def scheduleListK (K : Nat) (rs : List Rot) : RotProg
*The K-bounded compiler**: fold the sequence through K-capped ASAP insertion.
theoreminsertASAPK_denote
theorem insertASAPK_denote (K : Nat) (n : Nat) (r : Rot) (p : RotProg)
    (hb : RotsBounded n p) :
    RotProg.denote n (insertASAPK K r p)
      = Rot.denote n r * RotProg.denote n p
theoreminsertASAPK_bounded
theorem insertASAPK_bounded (K n : Nat) (r : Rot)
    (hr : sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n)
    (p : RotProg) (hb : RotsBounded n p) :
    RotsBounded n (insertASAPK K r p)
theoremscheduleListK_denote_aux
private theorem scheduleListK_denote_aux (K n : Nat) :
    ∀ (rs : List Rot) (acc : RotProg),
      (∀ r ∈ rs, sortedStrict r.axis = true
        ∧ PauliProduct.width r.axis ≤ n) →
      RotsBounded n acc →
      RotProg.denote n (rs.foldl (fun a r => insertASAPK K r a) acc)
        = seqDenote n rs * RotProg.denote n acc
  | [], acc, _, _ =>
theoremscheduleListK_denote
theorem scheduleListK_denote (K n : Nat) (rs : List Rot)
    (hrs : ∀ r ∈ rs, sortedStrict r.axis = true
      ∧ PauliProduct.width r.axis ≤ n) :
    RotProg.denote n (scheduleListK K rs) = seqDenote n rs
*SEMANTIC PRESERVATION**: the K-bounded compiler's layered program denotes EXACTLY the input sequence.
deflayersLE
def layersLE (K : Nat) (p : RotProg) : Bool
Layer sizes of a program all within `K`.
theoreminsertASAPK_layers
theorem insertASAPK_layers (K : Nat) (hK : 1 ≤ K) (r : Rot) (p : RotProg)
    (hp : layersLE K p = true) :
    layersLE K (insertASAPK K r p) = true
theoremscheduleListK_layers
theorem scheduleListK_layers (K : Nat) (hK : 1 ≤ K) (rs : List Rot) :
    layersLE K (scheduleListK K rs) = true
*HARDWARE VALIDITY**: every layer of the compiled program has at most `K` rotations.
theoreminsertASAPK_countAngle
theorem insertASAPK_countAngle (K : Nat) (a : RAngle) (r : Rot)
    (p : RotProg) :
    countAngle a (insertASAPK K r p)
      = countAngle a p + (if r.angle == a then 1 else 0)
theoremfoldl_countAngle
private theorem foldl_countAngle (K : Nat) (a : RAngle) :
    ∀ (rs : List Rot) (acc : RotProg),
      countAngle a (rs.foldl (fun acc r => insertASAPK K r acc) acc)
        = countAngle a acc + rs.countP (fun r => r.angle == a)
  | [], acc => by simp
  | r :: rs, acc =>
theoremscheduleListK_countAngle
theorem scheduleListK_countAngle (K : Nat) (a : RAngle) (rs : List Rot) :
    countAngle a (scheduleListK K rs)
      = rs.countP (fun r => r.angle == a)
*Per-angle counts survive K-bounded compilation on the nose.**
theoremscheduleListK_countPi8
theorem scheduleListK_countPi8 (K : Nat) (rs : List Rot) :
    countPi8 (scheduleListK K rs)
      = rs.countP (fun r => r.angle == RAngle.piEighth)
*The T-count survives K-bounded compilation.**
theoremcountRot_eq_sum
theorem countRot_eq_sum (p : RotProg) :
    countRot p = (p.map List.length).sum
Total rotations of a program = sum of layer sizes.
theoremcountRot_le_K_mul_depth
theorem countRot_le_K_mul_depth (K : Nat) (p : RotProg)
    (hv : layersLE K p = true) :
    countRot p ≤ K * rotDepth p
*THE UNIVERSAL LOWER BOUND**: any K-valid layered program packs at most `K` rotations per layer, so `N ≤ K · depth` — i.e. depth ≥ ⌈N/K⌉ for EVERY compiler respecting the hardware cap.
theoremscheduleListK_depth_le
theorem scheduleListK_depth_le (K : Nat) (rs : List Rot) :
    rotDepth (scheduleListK K rs) ≤ rs.length
The number of layers the greedy K-compiler produces never exceeds the sequence length.
theoremcountRot_insertASAPK
theorem countRot_insertASAPK (K : Nat) (r : Rot) (p : RotProg) :
    countRot (insertASAPK K r p) = countRot p + 1
theoremcountRot_scheduleListK
theorem countRot_scheduleListK (K : Nat) (rs : List Rot) :
    countRot (scheduleListK K rs) = rs.length
defpacked
def packed (K : Nat) : RotProg → Bool
  | [] => true
  | [L] => decide (1 ≤ L.length) && decide (L.length ≤ K)
  | L :: rest => decide (L.length = K) && packed K rest
The greedy-fill shape: every layer FULL (`= K`) except possibly the last, which is nonempty and within the cap.
theoreminsertASAPK_mem
theorem insertASAPK_mem (K : Nat) (r : Rot) :
    ∀ (p : RotProg) (L : RotLayer) (s : Rot),
      L ∈ insertASAPK K r p → s ∈ L →
      (∃ L' ∈ p, s ∈ L') ∨ s = r
Every element placed by K-bounded insertion is an old element or the inserted rotation.
theoreminsertASAPK_ne_nil
theorem insertASAPK_ne_nil (K : Nat) (r : Rot) :
    ∀ (p : RotProg), insertASAPK K r p ≠ []
  | [] => by simp [insertASAPK]
  | L :: rest =>
theoreminsertASAPK_packed
theorem insertASAPK_packed (K : Nat) (hK : 1 ≤ K) (r : Rot) :
    ∀ (acc : RotProg),
      (∀ L ∈ acc, ∀ s ∈ L, commF s.axis r.axis = true) →
      packed K acc = true →
      packed K (insertASAPK K r acc) = true
*The greedy-fill lemma**: when the inserted rotation commutes with everything placed, K-bounded insertion preserves the packed shape.
theorempacked_depth
theorem packed_depth (K : Nat) (hK : 1 ≤ K) :
    ∀ (p : RotProg), packed K p = true →
      rotDepth p = (countRot p + K - 1) / K
Packed programs have depth EXACTLY ⌈count/K⌉.
defallCommB
def allCommB : List Rot → Bool
  | [] => true
  | r :: t => t.all (fun s => commF r.axis s.axis) && allCommB t
The pairwise-commuting hypothesis, decidable on the flat sequence (`a` before `b` ⇒ `commF a.axis b.axis`).
theoremfoldl_packed
private theorem foldl_packed (K : Nat) (hK : 1 ≤ K) :
    ∀ (rs : List Rot) (acc : RotProg),
      allCommB rs = true →
      (∀ L ∈ acc, ∀ s ∈ L, ∀ r' ∈ rs, commF s.axis r'.axis = true) →
      packed K acc = true →
      packed K (rs.foldl (fun a r => insertASAPK K r a) acc) = true
  | [], _, _, _, hp => hp
  | r :: rs, acc, hcomm, hsub, hp =>
theoremscheduleListK_depth_eq
theorem scheduleListK_depth_eq (K : Nat) (hK : 1 ≤ K) (rs : List Rot)
    (hcomm : allCommB rs = true) :
    rotDepth (scheduleListK K rs) = (rs.length + K - 1) / K
*VERIFIED OPTIMALITY (achievability)**: for a pairwise-commuting sequence — a PHASE POLYNOMIAL, e.g. the CCZ/adder layers of QianXu-style circuits — the K-bounded compiler achieves depth EXACTLY ⌈N/K⌉.
theoremscheduleListK_optimal
theorem scheduleListK_optimal (K : Nat) (hK : 1 ≤ K) (rs : List Rot)
    (hcomm : allCommB rs = true)
    (q : RotProg) (hqv : layersLE K q = true)
    (hqc : countRot q = rs.length) :
    rotDepth (scheduleListK K rs) ≤ rotDepth q
*VERIFIED OPTIMALITY (no compiler can beat it)**: any K-valid layered program implementing the same rotation count needs at least as many layers — the ⌈N/K⌉ sandwich closes.

FormalRV.PauliRotation.Compiler.ToPPM.BlockIdentities

FormalRV/PauliRotation/Compiler/ToPPM/BlockIdentities.lean
FormalRV.PauliRotation.Compiler.ToPPM.BlockIdentities ──────────────────────────────────────────── Remaining prerequisites for the π/8 teleport-block identities: • `yMat_mulVec` — the `Y_t` action collapse (bit flip with `±i` phase), • `mulVec_yn_tensorHigh` — ancilla `Y_n`: `(α, β) ↦ (−iβ, iα)`, • `axisMat_snoc_split` — the lowering's joint axis `P ++ [Z_n]` splits off its ancilla factor (disjoint supports, order-free), • `mulVec_joint_tensorHigh` — the joint axis acts as `data-action ⊗ (α, −β)`.
theoremyMat_mulVec
theorem yMat_mulVec (n t : Nat) (ht : t < n) (v : Fin (2 ^ n) → ℂ)
    (i : Fin (2 ^ n)) :
    ((axisMat n [(⟨t, .y⟩ : PFactor)]).mulVec v) i
      = (if ((flipT n t ht i : Fin (2 ^ n)) : Nat).testBit t
          then -Complex.I else Complex.I) * v (flipT n t ht i)
`Y_t` acts on vectors by the bit flip with the `±i` phase.
theoremmulVec_yn_tensorHigh
theorem mulVec_yn_tensorHigh (n : Nat) (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    (axisMat (n + 1) [(⟨n, .y⟩ : PFactor)]).mulVec (tensorHigh n α β ψ)
      = tensorHigh n (-Complex.I * β) (Complex.I * α) ψ
*Ancilla `Y_n`: `(α, β) ↦ (−iβ, iα)`.**
theoremaxisMat_snoc_split
theorem axisMat_snoc_split (n : Nat) (P : PauliProduct) (f : PFactor)
    (hw : ∀ g ∈ P, g.qubit < f.qubit) :
    axisMat n (P ++ [f]) = axisMat n P * axisMat n [f]
An axis whose LAST factor sits above all others splits it off multiplicatively (disjoint supports — no sorting needed beyond the bound).
theoremmulVec_joint_tensorHigh
theorem mulVec_joint_tensorHigh (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    (axisMat (n + 1) (P ++ [⟨n, .z⟩])).mulVec (tensorHigh n α β ψ)
      = tensorHigh n α (-β) ((axisMat n P).mulVec ψ)
*The lowering's joint measurement axis**: `P·Z_n` acts on the split as the data action of `P` with the ancilla sign flip.

FormalRV.PauliRotation.Compiler.ToPPM.CCZBlock

FormalRV/PauliRotation/Compiler/ToPPM/CCZBlock.lean
FormalRV.PauliRotation.Compiler.ToPPM.CCZBlock ───────────────────────────────────── *THE 1-CCZ TELEPORT LANE — state machinery.** `tensorTriple m f ψ` is `ψ ⊗ |φ_f⟩` with a THREE-ancilla block at wires `m, m+1, m+2` whose (possibly ENTANGLED) amplitudes are `f y₁ y₂ y₃` — the `|CCZ⟩ = CCZ|+++⟩` resource is `f = cczF` (amplitude `−1` exactly on `111`). The action lemmas: • data-wire `Z_d` passes through (`mulVec_zd_tensorTriple`), • ancilla `Z_{m+i}` re-signs the `i`-th amplitude slot, • ancilla `X_{m+i}` flips the `i`-th amplitude slot, from which every axis the CCZ block measures (joints `Z_d·Z_a`, twisted destructions `X_a·Z·Z`, corrections `Z_d`) decomposes by the proven splits. The numerically pinned target (verified on all 64 branches): Corr(m,b)·Π_b(twisted)·Π_m(joints) (ψ ⊗ cczF) = ⅛·(−1)^{⟨m,b⟩} • (CCZ_{d₁d₂d₃} ψ) ⊗ collapse(m,b) collapse(m,b) y = (−1)^{⟨b,y⟩ ⊕ m₃y₁y₂ ⊕ m₂y₁y₃ ⊕ m₁y₂y₃}.
deflowBits3
def lowBits3 (m : Nat) (M : Fin (2 ^ (m + 3))) : Fin (2 ^ m)
deftensorTriple
noncomputable def tensorTriple (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) : Fin (2 ^ (m + 3)) → ℂ
`ψ ⊗ |φ_f⟩`: three ancillas at wires `m, m+1, m+2` with joint amplitudes `f` (not necessarily a product state).
theoremtensorTriple_vec_add
theorem tensorTriple_vec_add (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ φ : Fin (2 ^ m) → ℂ) :
    tensorTriple m f (ψ + φ)
      = tensorTriple m f ψ + tensorTriple m f φ
theoremtensorTriple_vec_smul
theorem tensorTriple_vec_smul (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (c : ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    tensorTriple m f (c • ψ) = c • tensorTriple m f ψ
theoremtensorTriple_f_add
theorem tensorTriple_f_add (m : Nat) (f g : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    tensorTriple m (fun a b c => f a b c + g a b c) ψ
      = tensorTriple m f ψ + tensorTriple m g ψ
theoremtensorTriple_f_smul
theorem tensorTriple_f_smul (m : Nat) (c : ℂ) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    tensorTriple m (fun a b d => c * f a b d) ψ
      = c • tensorTriple m f ψ
theoremlowBits3_testBit
theorem lowBits3_testBit (m : Nat) (M : Fin (2 ^ (m + 3))) (q : Nat)
    (hq : q < m) :
    ((lowBits3 m M : Fin (2 ^ m)) : Nat).testBit q = (M : Nat).testBit q
theoremlowBits3_flip
theorem lowBits3_flip (m : Nat) (M : Fin (2 ^ (m + 3))) (i : Nat)
    (hi : m ≤ i) (hi3 : i < m + 3) :
    lowBits3 m (flipT (m + 3) i (by omega) M) = lowBits3 m M
theoremmulVec_zd_tensorTriple
theorem mulVec_zd_tensorTriple (m d : Nat) (hd : d < m)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨d, .z⟩ : PFactor)]).mulVec (tensorTriple m f ψ)
      = tensorTriple m f ((axisMat m [(⟨d, .z⟩ : PFactor)]).mulVec ψ)
Data-wire `Z_d` passes through.
theoremmulVec_za_tensorTriple
theorem mulVec_za_tensorTriple (m : Nat) (i : Fin 3)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m + (i : Nat), .z⟩ : PFactor)]).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ =>
            (if (match (i : Nat) with | 0 => y₁ | 1 => y₂ | _ => y₃)
             then (-1 : ℂ) else 1) * f y₁ y₂ y₃) ψ
Ancilla `Z_{m+i}` re-signs the corresponding amplitude slot.
theoremmulVec_xa_tensorTriple
theorem mulVec_xa_tensorTriple (m : Nat) (i : Fin 3)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m + (i : Nat), .x⟩ : PFactor)]).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ =>
            match (i : Nat) with
            | 0 => f (!y₁) y₂ y₃
            | 1 => f y₁ (!y₂) y₃
            | _ => f y₁ y₂ (!y₃)) ψ
Ancilla `X_{m+i}` flips the corresponding amplitude slot.
theoremmulVec_joint_tt
theorem mulVec_joint_tt (m d : Nat) (hd : d < m) (i : Fin 3)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨d, .z⟩ : PFactor), ⟨m + (i : Nat), .z⟩]).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ =>
            (if (match (i : Nat) with | 0 => y₁ | 1 => y₂ | _ => y₃)
             then (-1 : ℂ) else 1) * f y₁ y₂ y₃)
          ((axisMat m [(⟨d, .z⟩ : PFactor)]).mulVec ψ)
The joint measurement axis `Z_d · Z_{m+i}` acts as the data `Z_d` times the slot-`i` sign.
theoremmulVec_za0_tt
theorem mulVec_za0_tt (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m, .z⟩ : PFactor)]).mulVec (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => (if y₁ then (-1 : ℂ) else 1) * f y₁ y₂ y₃) ψ
Specialized clean-index corollaries (defeq instances of the `Fin 3` lemmas).
theoremmulVec_za1_tt
theorem mulVec_za1_tt (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m + 1, .z⟩ : PFactor)]).mulVec (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => (if y₂ then (-1 : ℂ) else 1) * f y₁ y₂ y₃) ψ
theoremmulVec_za2_tt
theorem mulVec_za2_tt (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m + 2, .z⟩ : PFactor)]).mulVec (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => (if y₃ then (-1 : ℂ) else 1) * f y₁ y₂ y₃) ψ
theoremmulVec_xa0_tt
theorem mulVec_xa0_tt (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m, .x⟩ : PFactor)]).mulVec (tensorTriple m f ψ)
      = tensorTriple m (fun y₁ y₂ y₃ => f (!y₁) y₂ y₃) ψ
theoremmulVec_xa1_tt
theorem mulVec_xa1_tt (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m + 1, .x⟩ : PFactor)]).mulVec (tensorTriple m f ψ)
      = tensorTriple m (fun y₁ y₂ y₃ => f y₁ (!y₂) y₃) ψ
theoremmulVec_xa2_tt
theorem mulVec_xa2_tt (m : Nat) (f : Bool → Bool → Bool → ℂ)
    (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨m + 2, .x⟩ : PFactor)]).mulVec (tensorTriple m f ψ)
      = tensorTriple m (fun y₁ y₂ y₃ => f y₁ y₂ (!y₃)) ψ
deftwf
noncomputable def twf (t y : Bool) : ℂ
The twist factor `(if t ∧ y then −1 else 1)`.
theoremmulVec_dest1_tt
theorem mulVec_dest1_tt (m : Nat) (t₂ t₃ : Bool)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) ((⟨m, .x⟩ : PFactor)
        :: ((if t₂ then [(⟨m + 1, .z⟩ : PFactor)] else [])
            ++ (if t₃ then [(⟨m + 2, .z⟩ : PFactor)] else [])))).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => twf t₂ y₂ * twf t₃ y₃ * f (!y₁) y₂ y₃) ψ
Destruction axis on ancilla 1: `X_m · Z_{m+1}^{t₂} · Z_{m+2}^{t₃}`.
theoremmulVec_dest2_tt
theorem mulVec_dest2_tt (m : Nat) (t₁ t₃ : Bool)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) ((if t₁ then [(⟨m, .z⟩ : PFactor)] else [])
        ++ ((⟨m + 1, .x⟩ : PFactor)
            :: (if t₃ then [(⟨m + 2, .z⟩ : PFactor)] else [])))).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => twf t₁ y₁ * twf t₃ y₃ * f y₁ (!y₂) y₃) ψ
Destruction axis on ancilla 2: `Z_m^{t₁} · X_{m+1} · Z_{m+2}^{t₃}`.
theoremmulVec_dest3_tt
theorem mulVec_dest3_tt (m : Nat) (t₁ t₂ : Bool)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) ((if t₁ then [(⟨m, .z⟩ : PFactor)] else [])
        ++ ((if t₂ then [(⟨m + 1, .z⟩ : PFactor)] else [])
            ++ [(⟨m + 2, .x⟩ : PFactor)]))).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => twf t₁ y₁ * twf t₂ y₂ * f y₁ y₂ (!y₃)) ψ
Destruction axis on ancilla 3: `Z_m^{t₁} · Z_{m+1}^{t₂} · X_{m+2}`.
theoremmulVec_joint1_tt
theorem mulVec_joint1_tt (m d : Nat) (hd : d < m)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨d, .z⟩ : PFactor), ⟨m, .z⟩]).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => (if y₁ then (-1 : ℂ) else 1) * f y₁ y₂ y₃)
          ((axisMat m [(⟨d, .z⟩ : PFactor)]).mulVec ψ)
Joint specializations at the three concrete ancilla wires.
theoremmulVec_joint2_tt
theorem mulVec_joint2_tt (m d : Nat) (hd : d < m)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨d, .z⟩ : PFactor), ⟨m + 1, .z⟩]).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => (if y₂ then (-1 : ℂ) else 1) * f y₁ y₂ y₃)
          ((axisMat m [(⟨d, .z⟩ : PFactor)]).mulVec ψ)
theoremmulVec_joint3_tt
theorem mulVec_joint3_tt (m d : Nat) (hd : d < m)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    (axisMat (m + 3) [(⟨d, .z⟩ : PFactor), ⟨m + 2, .z⟩]).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m
          (fun y₁ y₂ y₃ => (if y₃ then (-1 : ℂ) else 1) * f y₁ y₂ y₃)
          ((axisMat m [(⟨d, .z⟩ : PFactor)]).mulVec ψ)
theoremmulVec_corr_tt
theorem mulVec_corr_tt (m d : Nat) (hd : d < m) (p : Bool)
    (f : Bool → Bool → Bool → ℂ) (ψ : Fin (2 ^ m) → ℂ) :
    ((if p then axisMat (m + 3) [(⟨d, .z⟩ : PFactor)] else 1)).mulVec
        (tensorTriple m f ψ)
      = tensorTriple m f
          ((if p then axisMat m [(⟨d, .z⟩ : PFactor)] else 1).mulVec ψ)
A parity-conditioned `Z_d` correction passes to the data factor with the parity SYMBOLIC.
theoremcorr_entry
theorem corr_entry (m d : Nat) (p : Bool) (hd : d < m)
    (v : Fin (2 ^ m) → ℂ) (j : Fin (2 ^ m)) :
    ((if p then axisMat m [(⟨d, .z⟩ : PFactor)] else 1).mulVec v) j
      = (if p && (j : Nat).testBit d then (-1 : ℂ) else 1) * v j
Symbolic-parity correction at the data-entry level.
defcczF
noncomputable def cczF : Bool → Bool → Bool → ℂ
The `|CCZ⟩` resource amplitudes (`−1` exactly on `111`).
defcczCollapse
noncomputable def cczCollapse (m₁ m₂ m₃ b₁ b₂ b₃ : Bool) :
    Bool → Bool → Bool → ℂ
The collapsed ancilla amplitudes on branch `(m, b)` — the `b`-character times the `m`-driven graph-state quadratic.
defcczSign
noncomputable def cczSign (m₁ m₂ m₃ b₁ b₂ b₃ : Bool) : ℂ
The branch sign `(−1)^{⟨m,b⟩}`.
theoremtw_xor
theorem tw_xor (a b : Bool) :
    (if (a ^^ b) then (-1 : ℂ) else 1)
      = (if a then (-1 : ℂ) else 1) * (if b then (-1 : ℂ) else 1)
Sign-atom algebra for the symbolic leaf closure.
theoremtw_sq
theorem tw_sq (c : Bool) :
    (if c then (-1 : ℂ) else 1) ^ 2 = 1
theoremtw_cube
theorem tw_cube (c : Bool) :
    (if c then (-1 : ℂ) else 1) ^ 3 = (if c then (-1 : ℂ) else 1)
theoremtw_pow_four
theorem tw_pow_four (c : Bool) :
    (if c then (-1 : ℂ) else 1) ^ 4 = 1

FormalRV.PauliRotation.Compiler.ToPPM.CCZBlockBranch

FormalRV/PauliRotation/Compiler/ToPPM/CCZBlockBranch.lean
FormalRV.PauliRotation.Compiler.ToPPM.CCZBlockBranch ─────────────────────────────────────────── *FENCED — the 64-branch CCZ-block semantic theorem.** The statement is EXACTLY the closed form validated branch-exactly by the independent Qiskit suite (`scripts/ppm_qiskit_validation.py`, route-B section: all 64 branches, Born sum 1). The Lean proof is a 4096-leaf arithmetic case bash (64 index contexts x 64 outcome combinations, each closed by norm_num) — mathematically routine but hours of elaboration, so it lives OUTSIDE the umbrella and compiles on its own schedule. Nothing downstream depends on it: the lane's emitter, recognizer, and count theorems are proven in CCZLane.lean.
theoremcczBlock_branch
theorem cczBlock_branch (m d₁ d₂ d₃ : Nat)
    (h₁ : d₁ < m) (h₂ : d₂ < m) (h₃ : d₃ < m)
    (m₁ m₂ m₃ b₁ b₂ b₃ : Bool) (ψ : Fin (2 ^ m) → ℂ) :
    (if b₃ ^^ (m₁ && m₂) then axisMat (m + 3) [(⟨d₃, .z⟩ : PFactor)]
        else 1).mulVec
      ((if b₂ ^^ (m₁ && m₃) then axisMat (m + 3) [(⟨d₂, .z⟩ : PFactor)]
          else 1).mulVec
        ((if b₁ ^^ (m₂ && m₃) then axisMat (m + 3) [(⟨d₁, .z⟩ : PFactor)]
            else 1).mulVec
          ((projHalf (axisMat (m + 3)
              ((if m₂ then [(⟨m, .z⟩ : PFactor)] else [])
                ++ ((if m₁ then [(⟨m + 1, .z⟩ : PFactor)] else [])
*THE CCZ-BLOCK BRANCH THEOREM (all 64 branches)**: three joint `Z_{d_i}Z_{a_i}` measurements against `|CCZ⟩`, the `m`-selected TWISTED destructions, and the quadratic-parity `Z` corrections implement EXACTLY the CCZ gate on the data, with explicit branch scalar `⅛·(−1)^{⟨m,b⟩}` and the collapsed (graph-state) ancillas. Numerically pinned, now machine-checked.

FormalRV.PauliRotation.Compiler.ToPPM.CCZLane

FormalRV/PauliRotation/Compiler/ToPPM/CCZLane.lean
FormalRV.PauliRotation.Compiler.ToPPM.CCZLane ──────────────────────────────────── *THE 1-CCZ LOWERING MODE — statements, recognizer, economics.** `cczBlock d₁ d₂ d₃ a c` is THE PPM program of the CCZ-state teleport (Qiskit-validated branch-exact on all 64 branches): useCCZ[a,a+1,a+2]; c = Measure Z[d₁]Z[a]; c+1 = Measure Z[d₂]Z[a+1]; c+2 = Measure Z[d₃]Z[a+2]; c+3 = MeasureSel2 (c+2; c+1) X[a]… (CZ-conjugated bases) c+4 = MeasureSel2 (c+2; c) X[a+1]… c+5 = MeasureSel2 (c+1; c) X[a+2]… if c+3 ^^ (c+1)*(c+2) == 1 then Z[d₁]; (quadratic corrections) if c+4 ^^ c*(c+2) == 1 then Z[d₂]; if c+5 ^^ c*(c+1) == 1 then Z[d₃] `isCCZRots` recognizes the dictionary's seven-π/8 CCZ phase polynomial, and the count theorems give THE VERIFIED 8T-vs-1CCZ ECONOMICS: route A consumes 7 |T⟩; route B consumes 1 |CCZ⟩ (factory: 8 |T⟩).
defcczBlock
def cczBlock (d₁ d₂ d₃ a c : Nat) : PPMProg
The CCZ-state teleport block on data `d₁ d₂ d₃`, resource ancillas `a, a+1, a+2`, outcome slots `c..c+5`.
theoremcczBlock_magicCCZ
theorem cczBlock_magicCCZ (d₁ d₂ d₃ a c : Nat) :
    countMagicCCZ (cczBlock d₁ d₂ d₃ a c) = 1
Route B consumes EXACTLY ONE CCZ magic state.
theoremcczBlock_magicT
theorem cczBlock_magicT (d₁ d₂ d₃ a c : Nat) :
    countMagicT (cczBlock d₁ d₂ d₃ a c) = 0
Route B consumes NO T states.
theoremcczBlock_meas
theorem cczBlock_meas (d₁ d₂ d₃ a c : Nat) :
    countMeas (cczBlock d₁ d₂ d₃ a c) = 6
Route B: six measurements, six outcome slots.
theoremcczBlock_cwidth
theorem cczBlock_cwidth (d₁ d₂ d₃ a c : Nat) :
    PPMProg.cwidth (cczBlock d₁ d₂ d₃ a c) = 6
theoremcczRoute7T_magicT
theorem cczRoute7T_magicT (x y z a c : Nat) :
    countMagicT (lowerFlat a c (cczGate x y z).flatten) = 7
Route A (the dictionary's seven-π/8 phase polynomial, lowered rotation-by-rotation) consumes EXACTLY SEVEN T states.
theoremccz_route_tradeoff
theorem ccz_route_tradeoff (x y z a c d₁ d₂ d₃ a' c' : Nat) :
    countMagicT (lowerFlat a c (cczGate x y z).flatten) = 7
      ∧ countMagicCCZ (lowerFlat a c (cczGate x y z).flatten) = 0
      ∧ countMagicT (cczBlock d₁ d₂ d₃ a' c') = 0
      ∧ countMagicCCZ (cczBlock d₁ d₂ d₃ a' c') = 1
*THE 8T-vs-1CCZ TRADE, VERIFIED**: per CCZ layer, route A costs 7 |T⟩ and 0 |CCZ⟩; route B costs 0 |T⟩ and 1 |CCZ⟩ (one factory output; the standard factory distills it from 8 |T⟩). Which is cheaper is now an AUDIT-LEVEL knob on verified numbers, not a modelling assumption.
defisCCZRots
def isCCZRots : List Rot → Option (Nat × Nat × Nat)
  | [⟨false, .piEighth, [⟨x₁, .z⟩]⟩,
     ⟨false, .piEighth, [⟨y₁, .z⟩]⟩,
     ⟨false, .piEighth, [⟨z₁, .z⟩]⟩,
     ⟨true,  .piEighth, [⟨x₂, .z⟩, ⟨y₂, .z⟩]⟩,
     ⟨true,  .piEighth, [⟨x₃, .z⟩, ⟨z₂, .z⟩]⟩,
     ⟨true,  .piEighth, [⟨y₃, .z⟩, ⟨z₃, .z⟩]⟩,
     ⟨false, .piEighth, [⟨x₄, .z⟩, ⟨y₄, .z⟩, ⟨z₄, .z⟩]⟩] =>
      if x₁ = x₂ ∧ x₁ = x₃ ∧ x₁ = x₄ ∧ y₁ = y₂ ∧ y₁ = y₃ ∧ y₁ = y₄
          ∧ z₁ = z₂ ∧ z₁ = z₃ ∧ z₁ = z₄ ∧ x₁ < y₁ ∧ y₁ < z₁
      then some (x₁, y₁, z₁) else none
  | _ => none
Recognize the dictionary's CCZ phase polynomial (the exact seven-rotation pattern `cczGate x y z` emits, `x < y < z`).
theoremisCCZRots_sound
theorem isCCZRots_sound (rs : List Rot) (x y z : Nat)
    (h : isCCZRots rs = some (x, y, z)) :
    rs = (cczGate x y z).flatten ∧ x < y ∧ y < z
The recognizer is SOUND: a hit IS the dictionary's CCZ polynomial.
theoremisCCZRots_complete
theorem isCCZRots_complete (x y z : Nat) (hxy : x < y) (hyz : y < z) :
    isCCZRots (cczGate x y z).flatten = some (x, y, z)
The recognizer FIRES on every dictionary CCZ (completeness on the compiler's own output).

FormalRV.PauliRotation.Compiler.ToPPM.Embed

FormalRV/PauliRotation/Compiler/ToPPM/Embed.lean
FormalRV.PauliRotation.Compiler.ToPPM.Embed ────────────────────────────────── *THE EMBEDDING LAYER**: a lowered block's statements act on the wires `< n`, so their action passes through a top split `ψ ⊗ (α,β)` at wire `n` untouched. Iterating this is how block `i` of the lowered program acts on the joint state `ψ ⊗ anc_i ⊗ … ⊗ anc_k`: the outer ancillas are spectators. §1 vector linearity of the split, §2 the `Y_q` data-wire pass-through (completing Z/X/Y), §3 the KIND-FREE axis pass-through (`mulVec_axis_tensorHigh'`), §4 statement- and program-level pass-through (`stmtLow`, `stmtDenote_tensorHigh`, `progDenote_tensorHigh`).
theoremtensorHigh_vec_add
theorem tensorHigh_vec_add (n : Nat) (α β : ℂ) (φ φ' : Fin (2 ^ n) → ℂ) :
    tensorHigh n α β (φ + φ')
      = tensorHigh n α β φ + tensorHigh n α β φ'
theoremtensorHigh_vec_smul
theorem tensorHigh_vec_smul (n : Nat) (α β c : ℂ) (φ : Fin (2 ^ n) → ℂ) :
    tensorHigh n α β (c • φ) = c • tensorHigh n α β φ
theoremmulVec_yq_tensorHigh
theorem mulVec_yq_tensorHigh (n q : Nat) (hq : q < n) (α β : ℂ)
    (ψ : Fin (2 ^ n) → ℂ) :
    (axisMat (n + 1) [(⟨q, .y⟩ : PFactor)]).mulVec (tensorHigh n α β ψ)
      = tensorHigh n α β ((axisMat n [(⟨q, .y⟩ : PFactor)]).mulVec ψ)
theoremmulVec_axis_tensorHigh'
theorem mulVec_axis_tensorHigh' (n : Nat) :
    ∀ (P : PauliProduct), sortedStrict P = true →
      PauliProduct.width P ≤ n →
      ∀ (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ),
        (axisMat (n + 1) P).mulVec (tensorHigh n α β ψ)
          = tensorHigh n α β ((axisMat n P).mulVec ψ)
  | [], _, _, α, β, ψ =>
ANY sorted axis on wires `< n` passes through the split (Z, X, and Y factors alike).
defstmtLow
def stmtLow (n : Nat) : PPMStmt → Bool
  | .measure _ P => sortedStrict P && decide (PauliProduct.width P ≤ n)
  | .measureSel _ _ Pt Pe =>
      sortedStrict Pt && decide (PauliProduct.width Pt ≤ n)
        && sortedStrict Pe && decide (PauliProduct.width Pe ≤ n)
  | .measureSel2 _ _ _ P00 P01 P10 P11 =>
      sortedStrict P00 && decide (PauliProduct.width P00 ≤ n)
        && sortedStrict P01 && decide (PauliProduct.width P01 ≤ n)
        && sortedStrict P10 && decide (PauliProduct.width P10 ≤ n)
        && sortedStrict P11 && decide (PauliProduct.width P11 ≤ n)
  | .frame P => sortedStrict P && decide (PauliProduct.width P ≤ n)
  | .correct _ thn els =>
A statement is LOW for width `n` when every product it can apply is canonical and lives on wires `< n` (decidable).
theoremstmtDenote_tensorHigh
theorem stmtDenote_tensorHigh (n : Nat) (outs : List Bool) (b : Bool)
    (st : PPMStmt) (hst : stmtLow n st = true) (α β : ℂ)
    (ψ : Fin (2 ^ n) → ℂ) :
    (stmtDenote (n + 1) outs b st).mulVec (tensorHigh n α β ψ)
      = tensorHigh n α β ((stmtDenote n outs b st).mulVec ψ)
*A low statement acts through the split.**
theoremprogDenote_tensorHigh
theorem progDenote_tensorHigh (n : Nat) (ω : Nat → Bool) :
    ∀ (p : PPMProg) (outs : List Bool),
      (∀ st ∈ p, stmtLow n st = true) →
      ∀ (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ),
        (progDenote (n + 1) ω outs p).mulVec (tensorHigh n α β ψ)
          = tensorHigh n α β ((progDenote n ω outs p).mulVec ψ)
  | [], outs, _, α, β, ψ =>
*A low program acts through the split.**

FormalRV.PauliRotation.Compiler.ToPPM.GadgetLowering

FormalRV/PauliRotation/Compiler/ToPPM/GadgetLowering.lean
FormalRV.PauliRotation.Compiler.ToPPM.GadgetLowering ─────────────────────────────────────────── *THE GADGET-TO-PPM CAPSTONE**: gluing the preservation theorem (`lowerFlat_denote`) to the dictionary capstone (`gateRots_denote_applyNat`): every compiled Gate-IR gadget's LOWERED PPM PROGRAM implements the gadget's own Boolean semantics, up to `gphase` and the explicit branch scalar, tensored with the ancilla collapses — on EVERY measurement branch. `gateRots_kinds` discharges the Z/X side condition once and for all (every dictionary axis is Z/X by construction).
theoremkinds_hGate
theorem kinds_hGate (q : Nat) :
    ∀ r ∈ (hGate q).flatten, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremkinds_mk2
theorem kinds_mk2 (c t : Nat) (kc kt : PKind)
    (hc : kc = PKind.z ∨ kc = PKind.x) (ht : kt = PKind.z ∨ kt = PKind.x) :
    ∀ f ∈ mk2 c kc t kt, f.kind = PKind.z ∨ f.kind = PKind.x
theoremkinds_cnot
theorem kinds_cnot (c t : Nat) :
    ∀ r ∈ (cnotGate c t).flatten, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremkinds_ccz
theorem kinds_ccz (a b c : Nat) :
    ∀ r ∈ (cczGate a b c).flatten, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremgateRots_kinds
theorem gateRots_kinds (g : FormalRV.Framework.Gate) :
    ∀ r ∈ gateRots g, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
*Every compiled gadget axis uses only Z and X factors** — the kinds side condition of the preservation theorem, once and for all.
theoremlowerGate_denote
theorem lowerGate_denote (m : Nat) (g : FormalRV.Framework.Gate)
    (hops : opsOK g = true) (hw : width g ≤ m)
    (ω : Nat → Bool) (outs : List Bool) (ψ : Fin (2 ^ m) → ℂ) :
    (progDenote (ampsWidth m (ancAmps (gateRots g))) ω outs
        (lowerFlat m outs.length (gateRots g))).mulVec
      (stateOver (ancAmps (gateRots g)) (ancAmps (gateRots g)) m ψ)
    = (branchScalar ω (gateRots g) outs.length * gphase g)
        • stateOver (ancAmps (gateRots g))
            (ancOutAmps ω (gateRots g) outs.length) m
            ((applyMat m g).mulVec ψ)
*EVERY GATE-IR GADGET LOWERS TO PPM SEMANTICS-PRESERVINGLY**: on every measurement branch, the lowered PPM program of the compiled gadget, applied to `ψ ⊗ (magic/stabilizer ancillas)`, equals the explicit branch scalar times `gphase g` times the gadget's OWN Boolean semantics `applyMat m g` applied to the data, tensored with the collapsed ancillas.
theoremkinds_csDag
theorem kinds_csDag (t : Nat) :
    ∀ r ∈ csDagRots t, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremkinds_swap
theorem kinds_swap (i j : Nat) :
    ∀ r ∈ swapRots i j, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremkinds_bitRev
theorem kinds_bitRev (k : Nat) :
    ∀ r ∈ bitRevRots k, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremkinds_ladderLow
theorem kinds_ladderLow :
    ∀ (t : Nat), ∀ r ∈ aqftLadderLow t, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
  | 0, r, hr => by cases hr
  | t + 1, r, hr =>
theoremkinds_hLayer
theorem kinds_hLayer (k : Nat) :
    ∀ r ∈ hLayerRots k, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremkinds_aqft2
theorem kinds_aqft2 :
    ∀ (k : Nat), ∀ r ∈ aqft2Rots k, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
  | 0, r, hr => by cases hr
  | k + 1, r, hr =>
theoremkinds_qpe
theorem kinds_qpe (k : Nat) (oracle : List Rot)
    (horacle : ∀ r ∈ oracle, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x) :
    ∀ r ∈ qpeRots k oracle, ∀ f ∈ r.axis,
      f.kind = PKind.z ∨ f.kind = PKind.x
theoremlowerShorQPE_denote
theorem lowerShorQPE_denote (n k : Nat) (oracleG : FormalRV.Framework.Gate)
    (hops : opsOK oracleG = true) (hw : width oracleG ≤ n)
    (hk : k + 1 ≤ n)
    (hb : ∀ r ∈ qpeRots (k + 1) (gateRots oracleG),
        sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n)
    (ω : Nat → Bool) (outs : List Bool) (ψ : Fin (2 ^ n) → ℂ) :
    (progDenote
        (ampsWidth n (ancAmps (qpeRots (k + 1) (gateRots oracleG)))) ω outs
        (lowerFlat n outs.length (qpeRots (k + 1) (gateRots oracleG)))).mulVec
      (stateOver (ancAmps (qpeRots (k + 1) (gateRots oracleG)))
        (ancAmps (qpeRots (k + 1) (gateRots oracleG))) n ψ)
    = (branchScalar ω (qpeRots (k + 1) (gateRots oracleG)) outs.length
*THE FULL SHOR/QPE CIRCUIT LOWERS TO PPM SEMANTICS-PRESERVINGLY**: on every measurement branch, the lowered PPM program of the complete compiled algorithm — H-layer, modexp oracle, banded inverse QFT — applied to `ψ ⊗ ancillas`, equals the branch scalar times the composed closed form (IQFT block · oracle's `applyMat` · H-layer block) on the data, tensored with the ancilla collapses.

FormalRV.PauliRotation.Compiler.ToPPM.Induction

FormalRV/PauliRotation/Compiler/ToPPM/Induction.lean
FormalRV.PauliRotation.Compiler.ToPPM.Induction ────────────────────────────────────── *THE PRESERVATION INDUCTION — support layer.** `tensorAmps` builds `ψ ⊗ anc₁ ⊗ … ⊗ anc_k` by structural recursion whose widths line up DEFINITIONALLY (`ampsWidth m (a :: as) ≡ ampsWidth (m+1) as` — no `Nat.add`-associativity casts anywhere). The lemmas: • linearity of `tensorAmps` (smul), • `stmtLow_mono` and `progDenote_tensorAmps` — a low program acts on the innermost factor through ALL outer ancilla splits, • `extendTrace`/`progDenote_append` — the outcome-trace threading of sequential composition, • `rotOf_mulVec_tensorHigh`/`seqDenote_tensorHigh` — the ROTATION layer's own semantics passes through a split (the data factor of the induction composes at the bottom width).
defampsWidth
def ampsWidth (m : Nat) : List ℂ → Nat
  | [] => m
  | _ :: as => ampsWidth (m + 1) as
The width after adjoining one ancilla per listed amplitude.
defstateOver
noncomputable def stateOver :
    (skel : List ℂ) → (amps : List ℂ) → (m : Nat) → (Fin (2 ^ m) → ℂ)
      → (Fin (2 ^ ampsWidth m skel) → ℂ)
  | [], _, _, ψ => ψ
  | _ :: skel, [], m, ψ => stateOver skel [] (m + 1) (tensorHigh m 1 0 ψ)
  | _ :: skel, b :: bs, m, ψ =>
      stateOver skel bs (m + 1) (tensorHigh m 1 b ψ)
`ψ ⊗ (1, b₁) ⊗ … ⊗ (1, b_k)` with the WIDTH indexed by the skeleton `skel` alone — so input and output states of the preservation theorem (same skeleton, different amplitudes) share one type DEFINITIONALLY.
theoremampsWidth_le
theorem ampsWidth_le (as : List ℂ) : ∀ (m : Nat), m ≤ ampsWidth m as
theoremstateOver_smul
theorem stateOver_smul (skel : List ℂ) :
    ∀ (bs : List ℂ) (m : Nat) (c : ℂ) (ψ : Fin (2 ^ m) → ℂ),
      stateOver skel bs m (c • ψ) = c • stateOver skel bs m ψ
theoremstmtLow_mono
theorem stmtLow_mono (n n' : Nat) (h : n ≤ n') (st : PPMStmt)
    (hst : stmtLow n st = true) : stmtLow n' st = true
theoremprogDenote_stateOver
theorem progDenote_stateOver (skel : List ℂ) :
    ∀ (bs : List ℂ) (m : Nat) (p : PPMProg),
      (∀ st ∈ p, stmtLow m st = true) →
      ∀ (ω : Nat → Bool) (outs : List Bool) (ψ : Fin (2 ^ m) → ℂ),
        (progDenote (ampsWidth m skel) ω outs p).mulVec (stateOver skel bs m ψ)
          = stateOver skel bs m ((progDenote m ω outs p).mulVec ψ)
*A low program acts on the innermost factor through every split.**
defextendTrace
def extendTrace (ω : Nat → Bool) : List Bool → Nat → List Bool
  | outs, 0 => outs
  | outs, k + 1 => extendTrace ω (outs ++ [ω outs.length]) k
Extend an outcome trace by `k` fresh samples of `ω`.
theoremextendTrace_length
theorem extendTrace_length (ω : Nat → Bool) :
    ∀ (k : Nat) (outs : List Bool),
      (extendTrace ω outs k).length = outs.length + k
theoremprogDenote_append'
theorem progDenote_append' (d : Nat) (ω : Nat → Bool) :
    ∀ (p q : PPMProg) (outs : List Bool),
      progDenote d ω outs (p ++ q)
        = progDenote d ω (extendTrace ω outs (PPMProg.cwidth p)) q
            * progDenote d ω outs p
*Sequential composition splits with the trace threaded.**
theoremrotOf_mulVec_tensorHigh
theorem rotOf_mulVec_tensorHigh (n : Nat) (θ : ℝ) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    (rotOf θ (axisMat (n + 1) P)).mulVec (tensorHigh n α β ψ)
      = tensorHigh n α β ((rotOf θ (axisMat n P)).mulVec ψ)
theoremseqDenote_tensorHigh
theorem seqDenote_tensorHigh (n : Nat) :
    ∀ (rs : List Rot),
      (∀ r ∈ rs, sortedStrict r.axis = true
        ∧ PauliProduct.width r.axis ≤ n) →
      ∀ (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ),
        (seqDenote (n + 1) rs).mulVec (tensorHigh n α β ψ)
          = tensorHigh n α β ((seqDenote n rs).mulVec ψ)
  | [], _, α, β, ψ =>
A rotation sequence on data wires passes through a split.
defancAmps
noncomputable def ancAmps : List Rot → List ℂ
  | [] => []
  | r :: rs =>
      (match r.angle with
       | RAngle.piQuarter => [ancInAmp r]
       | RAngle.piEighth  => [ancInAmp r]
       | _ => []) ++ ancAmps rs
The ancilla input amplitudes a rotation list consumes (in order).
defancOutAmps
noncomputable def ancOutAmps (ω : Nat → Bool) : List Rot → Nat → List ℂ
  | [], _ => []
  | r :: rs, c =>
      (match r.angle with
       | RAngle.piQuarter => [ancOutAmp r (ω c) (ω (c + 1))]
       | RAngle.piEighth  => [ancOutAmp r (ω c) (ω (c + 1))]
       | _ => []) ++ ancOutAmps ω rs (c + rotSlots r)
The collapsed ancilla amplitudes, branch by branch.
defbranchScalar
noncomputable def branchScalar (ω : Nat → Bool) : List Rot → Nat → ℂ
  | [], _ => 1
  | r :: rs, c => rotScalar r (ω c) (ω (c + 1)) * branchScalar ω rs (c + rotSlots r)
The total branch scalar of a lowered rotation list.
theoremsortedStrict_append_single
theorem sortedStrict_append_single :
    ∀ (P : PauliProduct) (a : Nat) (k : PKind),
      sortedStrict P = true → (∀ f ∈ P, f.qubit < a) →
      sortedStrict (P ++ [⟨a, k⟩]) = true
  | [], _, _, _, _ => rfl
  | [f], a, k, _, hq =>
Sortedness survives appending the fresh top factor.
theoremwidth_append
theorem width_append :
    ∀ (P Q : PauliProduct),
      PauliProduct.width (P ++ Q)
        = max (PauliProduct.width P) (PauliProduct.width Q)
  | [], Q => by simp [PauliProduct.width]
  | f :: P, Q =>
Width of an appended product.
theoremqubit_lt_width
theorem qubit_lt_width :
    ∀ (P : PauliProduct), ∀ f ∈ P, f.qubit < PauliProduct.width P
  | f :: P, g, hg =>
Every qubit of an axis sits below its width.
theoremlowerRot_low
theorem lowerRot_low (m c : Nat) (r : Rot)
    (hs : sortedStrict r.axis = true)
    (hw : PauliProduct.width r.axis ≤ m) :
    ∀ st ∈ lowerRot m c r, stmtLow (m + 1) st = true
The lowered block's statements are all low for width `m + 1`.
theoremlowerFlat_denote
theorem lowerFlat_denote :
    ∀ (rs : List Rot) (m : Nat) (ψ : Fin (2 ^ m) → ℂ)
      (ω : Nat → Bool) (outs : List Bool),
      (∀ r ∈ rs, sortedStrict r.axis = true) →
      (∀ r ∈ rs, PauliProduct.width r.axis ≤ m) →
      (∀ r ∈ rs, ∀ f ∈ r.axis, f.kind = PKind.z ∨ f.kind = PKind.x) →
      (progDenote (ampsWidth m (ancAmps rs)) ω outs
          (lowerFlat m outs.length rs)).mulVec
        (stateOver (ancAmps rs) (ancAmps rs) m ψ)
      = branchScalar ω rs outs.length
          • stateOver (ancAmps rs) (ancOutAmps ω rs outs.length) m
              ((seqDenote m rs).mulVec ψ)
*EVERY ROTATION PROGRAM LOWERS TO PPM SEMANTICS-PRESERVINGLY**: on each outcome branch, the lowered PPM program applied to `ψ ⊗ (input ancillas)` equals the explicit branch scalar times `(seqDenote m rs · ψ) ⊗ (collapsed ancillas)` — the rotation layer's OWN matrix semantics on the data.

FormalRV.PauliRotation.Compiler.ToPPM.LoweredInstances

FormalRV/PauliRotation/Compiler/ToPPM/LoweredInstances.lean
FormalRV.PauliRotation.Compiler.ToPPM.LoweredInstances ───────────────────────────────────────────── *EVERY GADGET, FULLY LOWERED TO PPM WITH SEMANTIC CORRECTNESS** — the per-gadget instances of `lowerGate_denote`: each compiled arithmetic gadget's lowered PPM program implements the gadget's own Boolean semantics on every measurement branch (`LoweredOK`), plus the full Shor-15 instance through `lowerShorQPE_denote`. Together with the per-family compilation files, the symbolic T-counts, the scheduler theorems, the dictionary capstone, and the preservation theorem, this closes the chain Gate-IR ──gateRots──▶ rotations ──schedule──▶ layers ──lower──▶ PPM with machine-checked semantics and exact counts at EVERY arrow, for EVERY gadget and the complete Shor/QPE circuit.
defLoweredOK
def LoweredOK (g : FormalRV.Framework.Gate) : Prop
*The lowered-gadget correctness statement, packaged**: on every measurement branch, the lowered PPM program of `g` implements `gphase g • applyMat g` on the data, tensored with the ancilla collapses, at the explicit branch scalar.
theoremloweredOK_of
theorem loweredOK_of (g : FormalRV.Framework.Gate)
    (hops : opsOK g = true) : LoweredOK g
theoremcuccaroLowered
theorem cuccaroLowered : LoweredOK (cuccaro_n_bit_adder_full 4 0)
theoremcuccaroAddConstLowered
theorem cuccaroAddConstLowered : LoweredOK (cuccaro_addConstGate 3 0 5)
theoremcuccaroSubConstLowered
theorem cuccaroSubConstLowered : LoweredOK (cuccaro_subConstGate 3 0 5)
theoremcuccaroCompareLowered
theorem cuccaroCompareLowered :
    LoweredOK (cuccaro_compareConstForwardGate 3 0 5)
theoremcuccaroSubForwardLowered
theorem cuccaroSubForwardLowered :
    LoweredOK (cuccaro_subConstForwardOnlyGate 3 0 5)
theoremcuccaroSubReverseLowered
theorem cuccaroSubReverseLowered :
    LoweredOK (cuccaro_subConstReverseOnlyGate 3 0 5)
theoremgidneyLowered
theorem gidneyLowered : LoweredOK (gidney_adder 2)
theoremgidneyPatchedLowered
theorem gidneyPatchedLowered :
    LoweredOK (gidney_adder_full_faithful_no_measurement_patched 2)
theoremgidneyForwardRevLowered
theorem gidneyForwardRevLowered :
    LoweredOK (gidney_adder_forward_faithful_full_reverse_patched 2)
theoremcuccaroModAddLowered
theorem cuccaroModAddLowered :
    LoweredOK (sqir_style_modAddConst_clean_gate 3 5 2)
theoremcuccaroCtrlModAddLowered
theorem cuccaroCtrlModAddLowered :
    LoweredOK (sqir_style_controlledModAddConst_gate 3 2 5 2 1 0)
theoremgidneyAddConstLowered
theorem gidneyAddConstLowered : LoweredOK (addConstGate 2 1)
theoremgidneySubConstLowered
theorem gidneySubConstLowered : LoweredOK (subConstGate 2 1)
theoremgidneyCondAddLowered
theorem gidneyCondAddLowered : LoweredOK (conditionalAddConstGate 2 1 8)
theoremgidneyModAddLowered
theorem gidneyModAddLowered : LoweredOK (modAddConstGate 2 3 1)
theoremgidneyCtrlModAddLowered
theorem gidneyCtrlModAddLowered :
    LoweredOK (controlledModAddConstGate 2 3 1 9 10)
theoremmodMultConstLowered
theorem modMultConstLowered : LoweredOK (modmult_const_gate 2 15 7)
theoremmodMultMCPLowered
theorem modMultMCPLowered : LoweredOK (modmult_MCP_gate 2 15 7 13)
theoremshorModExpVerifiedLowered
theorem shorModExpVerifiedLowered :
    LoweredOK (shorModExpVerified 1 15 7 13)
theoremshorModExpLowered
theorem shorModExpLowered : LoweredOK (shorModExp 1 15 7)
theoremunaryLookupLowered
theorem unaryLookupLowered :
    LoweredOK (unary_lookup_multi_iteration 2 [([0], [5])])
theoremgrayLookupLowered
theorem grayLookupLowered :
    LoweredOK (grayLookupReadAt 2 (fun i => 6 + i) 1 (fun _ => 1))
theoremwindowedMulLowered
theorem windowedMulLowered : LoweredOK (windowedMulCircuit 2 4 3 2)
theoremwindowedModNMulLowered
theorem windowedModNMulLowered :
    LoweredOK (windowedModNMulCircuit 2 4 3 7 2)
theoremwindowedModNInPlaceLowered
theorem windowedModNInPlaceLowered :
    LoweredOK (windowedModNMulGate 2 4 7 2 3 5)
theoremgrayWindowedMulLowered
theorem grayWindowedMulLowered :
    LoweredOK (grayWindowedMulCircuitOf cuccaroAdder 2 4 3 2)
theoremshor15Lowered
theorem shor15Lowered (ω : Nat → Bool) (outs : List Bool)
    (ψ : Fin (2 ^ 7) → ℂ) :
    (progDenote
        (ampsWidth 7 (ancAmps
          (qpeRots 3 (gateRots (shorModExpVerified 1 15 7 13))))) ω outs
        (lowerFlat 7 outs.length
          (qpeRots 3 (gateRots (shorModExpVerified 1 15 7 13))))).mulVec
      (stateOver (ancAmps (qpeRots 3 (gateRots (shorModExpVerified 1 15 7 13))))
        (ancAmps (qpeRots 3 (gateRots (shorModExpVerified 1 15 7 13)))) 7 ψ)
    = (branchScalar ω (qpeRots 3 (gateRots (shorModExpVerified 1 15 7 13)))
          outs.length
        * (iqftPhase 2 * gphase (shorModExpVerified 1 15 7 13)
*The COMPLETE Shor-15 circuit — H-layer, verified modexp oracle, banded inverse QFT — lowered to a PPM measurement program, with semantic correctness on every measurement branch**: the lowered program implements the composed closed form (IQFT block · modexp `applyMat` · H-layer block) on the data, tensored with the ancilla collapses, at the explicit branch scalar. All side conditions kernel-checked.

FormalRV.PauliRotation.Compiler.ToPPM.Lowering

FormalRV/PauliRotation/Compiler/ToPPM/Lowering.lean
FormalRV.PauliRotation.Compiler.ToPPM.Lowering ───────────────────────────────────── *THE LOWERING `Rot → PPMProg` AND ITS BRANCH SEMANTICS.** §1 `stmtDenote`/`progDenote` — the per-outcome-branch MATRIX denotation of PPM programs (the denotational side of the operational `run`): measurements apply branch projectors, `measureSel` applies the parity-SELECTED projector, frames and fired corrections apply their Pauli matrices IMMEDIATELY (the decided convention), magic markers are semantically inert (resource audit only). §2 `lowerRot`/`lowerFlat` — one rotation becomes one teleport block: π ↦ (global phase −1; handled by the proven `dropPi` pre-pass) π/2 ↦ frame P (phase −i tracked) π/4 ↦ |Y⟩-block: c = Measure P·Z[a]; c' = Measure X[a]; if c ^^ c' == 1 then P (S-block, proven) π/8 ↦ |T⟩-block: useT[a]; c = Measure P·Z[a]; c' = MeasureIf c then Y[a] else X[a]; if c' == 1 then P (T-block, proven) Each π/4 and π/8 block consumes ONE fresh ancilla (wire counter `a`) and binds TWO outcome slots (counter `c`). Negative π/4 appends a `frame P` (since `e^{+iπ/4P} = iP·e^{−iπ/4P}`); negative π/8 uses the `|T†⟩` chirality of the SAME statements (the ancilla-state convention of the correctness theorem; the magic audit is identical). §3 Count transfer: `countMagicT ∘ lowerFlat` = number of π/8 rotations (THE T-count), measurement/slot bookkeeping, and well-formedness.
defstmtDenote
noncomputable def stmtDenote (d : Nat) (outs : List Bool) (outcome : Bool) :
    PPMStmt → Matrix (Fin (2 ^ d)) (Fin (2 ^ d)) ℂ
  | .measure _ P => projHalf (axisMat d P) outcome
  | .measureSel sel _ Pt Pe =>
      projHalf (axisMat d (if xorParity outs sel then Pt else Pe)) outcome
  | .measureSel2 sel1 sel2 _ P00 P01 P10 P11 =>
      projHalf (axisMat d
        (if xorParity outs sel1 then
          (if xorParity outs sel2 then P11 else P10)
         else (if xorParity outs sel2 then P01 else P00))) outcome
  | .frame P => axisMat d P
  | .correct par thn els =>
Per-outcome-branch matrix denotation of ONE statement at width `d`, given the outcome trace `outs` so far and this statement's `outcome`.
defprogDenote
noncomputable def progDenote (d : Nat) (ω : Nat → Bool) :
    List Bool → PPMProg → Matrix (Fin (2 ^ d)) (Fin (2 ^ d)) ℂ
  | _, [] => 1
  | outs, st :: p =>
      progDenote d ω (outs ++ List.replicate st.binds (ω outs.length)) p
        * stmtDenote d outs (ω outs.length) st
Per-outcome-branch denotation of a program (later statements act on the LEFT; the outcome stream `ω` indexes slots like the operational `run`).
defrotAnc
def rotAnc (r : Rot) : Nat
Ancillas one rotation consumes.
defrotSlots
def rotSlots (r : Rot) : Nat
Outcome slots one rotation binds.
deflowerRot
def lowerRot (a c : Nat) (r : Rot) : PPMProg
Lower ONE rotation at fresh ancilla `a`, next outcome slot `c`.
deflowerFlat
def lowerFlat (a c : Nat) : List Rot → PPMProg
  | []      => []
  | r :: rs => lowerRot a c r ++ lowerFlat (a + rotAnc r) (c + rotSlots r) rs
Lower a rotation sequence, threading the ancilla and slot counters.
defcountPi8L
def countPi8L (rs : List Rot) : Nat
π/8 rotations in a sequence (the sequence-level T-count).
theoremlowerRot_magicT
theorem lowerRot_magicT (a c : Nat) (r : Rot) :
    countMagicT (lowerRot a c r)
      = (if r.angle == RAngle.piEighth then 1 else 0)
theoremlowerFlat_magicT
theorem lowerFlat_magicT (rs : List Rot) :
    ∀ (a c : Nat), countMagicT (lowerFlat a c rs) = countPi8L rs
*THE T-COUNT TRANSFERS EXACTLY**: the lowered program consumes one T magic state per π/8 rotation — `countMagicT ∘ lower = countPi8`.
theoremlowerRot_cwidth
theorem lowerRot_cwidth (a c : Nat) (r : Rot) :
    PPMProg.cwidth (lowerRot a c r) = rotSlots r
theoremlowerFlat_cwidth
theorem lowerFlat_cwidth (rs : List Rot) :
    ∀ (a c : Nat),
      PPMProg.cwidth (lowerFlat a c rs) = (rs.map rotSlots).sum
Slot bookkeeping: the lowered program binds exactly `2` slots per π/4 and π/8 rotation.
theoremlowerFlat_magicCCZ
theorem lowerFlat_magicCCZ (rs : List Rot) :
    ∀ (a c : Nat), countMagicCCZ (lowerFlat a c rs) = 0
No CCZ states are consumed by the rotation-by-rotation route (the recognizer-driven `useCCZ` lane is the SECOND lowering mode).

FormalRV.PauliRotation.Compiler.ToPPM.RotStep

FormalRV/PauliRotation/Compiler/ToPPM/RotStep.lean
FormalRV.PauliRotation.Compiler.ToPPM.RotStep ──────────────────────────────────── *THE SINGLE-ROTATION STEP THEOREMS**: one rotation's lowered block, executed by the branch semantics `progDenote`, equals an explicit branch scalar times the rotation's OWN matrix semantics `Rot.denote` applied to the data — uniformly on every outcome branch (the emitted `correct` statement cancels the teleport's Pauli residue). • `lowerRot_denote_free` — π and π/2 (no ancilla, width `n`), • `lowerRot_denote_quarter` — the |Y⟩ S-block (ancilla at wire `n`), • `lowerRot_denote_eighth` — the |T⟩/|T†⟩ T-block (selective destruction, both chiralities). The data factor is `(Rot.denote n r).mulVec ψ` in every case, so the program induction composes these to `(seqDenote n rs).mulVec ψ` — the rotation layer's own semantics.
theoremxorParity_single
theorem xorParity_single (outs : List Bool) (c : Nat) :
    xorParity outs [c] = outs.getD c false
theoremxorParity_pair
theorem xorParity_pair (outs : List Bool) (c c' : Nat) :
    xorParity outs [c, c'] = (outs.getD c false ^^ outs.getD c' false)
theoremgetD_append_self
theorem getD_append_self (l : List Bool) (x : Bool) :
    (l ++ [x]).getD l.length false = x
theoremgetD_append_lt
theorem getD_append_lt (l l' : List Bool) (i : Nat) (hi : i < l.length) :
    (l ++ l').getD i false = l.getD i false
defancInAmp
noncomputable def ancInAmp (r : Rot) : ℂ
The ancilla input amplitude pair `(1, ancInAmp r)`.
defancOutAmp
noncomputable def ancOutAmp (r : Rot) (o₁ o₂ : Bool) : ℂ
The collapsed ancilla amplitude pair `(1, ancOutAmp r o₁ o₂)`.
defrotScalar
noncomputable def rotScalar (r : Rot) (o₁ o₂ : Bool) : ℂ
The branch scalar of one lowered rotation.
theoremlowerRot_denote_free
theorem lowerRot_denote_free (n : Nat) (r : Rot) (a c : Nat)
    (hanc : rotAnc r = 0)
    (ω : Nat → Bool) (outs : List Bool) (ψ : Fin (2 ^ n) → ℂ) :
    (progDenote n ω outs (lowerRot a c r)).mulVec ψ
      = rotScalar r (ω outs.length) (ω (outs.length + 1))
          • (Rot.denote n r).mulVec ψ
theoremgetD_two_snd
theorem getD_two_snd (outs : List Bool) (x y : Bool) :
    ((outs ++ [x]) ++ [y]).getD (outs.length + 1) false = y
theoremgetD_two_fst
theorem getD_two_fst (outs : List Bool) (x y : Bool) :
    ((outs ++ [x]) ++ [y]).getD outs.length false = x
theoremlowerRot_denote_eighth
theorem lowerRot_denote_eighth (n : Nat) (r : Rot)
    (hang : r.angle = RAngle.piEighth)
    (hs : sortedStrict r.axis = true)
    (hw : PauliProduct.width r.axis ≤ n)
    (hk : ∀ f ∈ r.axis, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ω : Nat → Bool) (outs : List Bool) (ψ : Fin (2 ^ n) → ℂ) :
    (progDenote (n + 1) ω outs (lowerRot n outs.length r)).mulVec
        (tensorHigh n 1 (ancInAmp r) ψ)
      = rotScalar r (ω outs.length) (ω (outs.length + 1))
          • tensorHigh n 1 (ancOutAmp r (ω outs.length) (ω (outs.length + 1)))
              ((Rot.denote n r).mulVec ψ)
*π/8 lowers correctly**: the lowered block on `ψ ⊗ |T^{(†)}⟩` (ancilla at wire `n`) equals the explicit branch scalar times `Rot.denote` applied to the data, tensored with the collapsed ancilla — on EVERY branch.
theoremaxisMat_mul_rotOf_quarter
theorem axisMat_mul_rotOf_quarter (n : Nat) (P : PauliProduct) :
    axisMat n P * rotOf (Real.pi / 4) (axisMat n P)
      = (-Complex.I) • rotOf (-(Real.pi / 4)) (axisMat n P)
The negative π/4 absorbs as `P·e^{−iπ/4 P} = −i·e^{+iπ/4 P}` (the appended `frame` plus phase).
theoremlowerRot_denote_quarter
theorem lowerRot_denote_quarter (n : Nat) (r : Rot)
    (hang : r.angle = RAngle.piQuarter)
    (hs : sortedStrict r.axis = true)
    (hw : PauliProduct.width r.axis ≤ n)
    (hk : ∀ f ∈ r.axis, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ω : Nat → Bool) (outs : List Bool) (ψ : Fin (2 ^ n) → ℂ) :
    (progDenote (n + 1) ω outs (lowerRot n outs.length r)).mulVec
        (tensorHigh n 1 (ancInAmp r) ψ)
      = rotScalar r (ω outs.length) (ω (outs.length + 1))
          • tensorHigh n 1 (ancOutAmp r (ω outs.length) (ω (outs.length + 1)))
              ((Rot.denote n r).mulVec ψ)
*π/4 lowers correctly**: the lowered S-block on `ψ ⊗ |Y⟩` (ancilla at wire `n`) equals the branch scalar times `Rot.denote` applied to the data, tensored with the collapsed ancilla — on EVERY branch.

FormalRV.PauliRotation.Compiler.ToPPM.SBlock

FormalRV/PauliRotation/Compiler/ToPPM/SBlock.lean
FormalRV.PauliRotation.Compiler.ToPPM.SBlock ─────────────────────────────────── *THE π/4 (CLIFFORD/S-LEVEL) TELEPORT-BLOCK IDENTITIES.** The lowering's S-block on data axis `P` with the `|Y⟩` ancilla at wire `n` (`|Y⟩ = (|0⟩ + i|1⟩)/√2` — a STABILIZER state, magic-free): c_a = Measure P·Z[n] c_b = Measure X[n] if c_a ^^ c_b == 1 then frame P Unlike the π/8 block, NO selective destruction is needed: the bad-branch correction of a π/4 rotation is `(−i)P` — Pauli with phase — so both measurements are FIXED and the correction fires on the XOR parity `c_a ^^ c_b`, exactly expressible by the ORIGINAL `correct` statement. The four branch identities (numerically pinned, then proven): (0,0): ½·e^{iπ/4} • (e^{−iπ/4 P}ψ) ⊗ |+⟩ (0,1): ½·e^{iπ/4} • (P·e^{−iπ/4 P}ψ) ⊗ |−⟩ (1,0): −½·e^{−iπ/4} • (P·e^{−iπ/4 P}ψ) ⊗ |+⟩ (1,1): ½·e^{−iπ/4} • (e^{−iπ/4 P}ψ) ⊗ |−⟩
theoremsBlock_branch_00
theorem sBlock_branch_00 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) false).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) false).mulVec
        (tensorHigh n 1 Complex.I ψ))
      = ((2⁻¹ : ℂ) * phaseC (Real.pi / 4))
          • tensorHigh n 1 1 ((rotOf (Real.pi / 4) (axisMat n P)).mulVec ψ)
*S-block branch (a=0, b=0)**: no correction.
theoremsBlock_branch_01
theorem sBlock_branch_01 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) true).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) false).mulVec
        (tensorHigh n 1 Complex.I ψ))
      = ((2⁻¹ : ℂ) * phaseC (Real.pi / 4))
          • tensorHigh n 1 (-1)
              ((axisMat n P).mulVec
                ((rotOf (Real.pi / 4) (axisMat n P)).mulVec ψ))
*S-block branch (a=0, b=1)**: correction `P` (parity 1).
theoremsBlock_branch_10
theorem sBlock_branch_10 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) false).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) true).mulVec
        (tensorHigh n 1 Complex.I ψ))
      = (-(2⁻¹ : ℂ) * phaseC (-(Real.pi / 4)))
          • tensorHigh n 1 1
              ((axisMat n P).mulVec
                ((rotOf (Real.pi / 4) (axisMat n P)).mulVec ψ))
*S-block branch (a=1, b=0)**: correction `P` (parity 1).
theoremsBlock_branch_11
theorem sBlock_branch_11 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) true).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) true).mulVec
        (tensorHigh n 1 Complex.I ψ))
      = ((2⁻¹ : ℂ) * phaseC (-(Real.pi / 4)))
          • tensorHigh n 1 (-1)
              ((rotOf (Real.pi / 4) (axisMat n P)).mulVec ψ)
*S-block branch (a=1, b=1)**: no correction (parity 0).

FormalRV.PauliRotation.Compiler.ToPPM.TBlock

FormalRV/PauliRotation/Compiler/ToPPM/TBlock.lean
FormalRV.PauliRotation.Compiler.ToPPM.TBlock ─────────────────────────────────── *B1 — THE π/8 TELEPORT-BLOCK IDENTITIES.** The lowering's T-block on data axis `P` with the `|T⟩` ancilla at wire `n`: c_a = Measure P·Z[n] c_b = MeasureIf c_a then Y[n] else X[n] (selective destruction) if c_b == 1 then frame P This file proves the four outcome branches in matrix-land: applying the branch projectors to `ψ ⊗ |T⟩` (amplitudes `(1, e^{iπ/4})`, the `1/√2` normalizations tracked in the explicit Born scalars) yields (scalar) • (correction ∘ e^{−iπ/8 P}) ψ ⊗ (collapsed ancilla) with the data correction `P` exactly when the SECOND outcome is `1` — i.e. the emitted `correct [c_b] P` statement is the right one, on every branch. The proofs are coefficient-wise `ring` identities after the double-angle substitution `π/4 = 2·(π/8)`; no Pythagorean relation and no normalization conventions are needed.
defprojHalf
noncomputable def projHalf {d : Type*} [Fintype d] [DecidableEq d]
    (M : Matrix d d ℂ) (b : Bool) : Matrix d d ℂ
The outcome-`b` branch projector of the ±1 observable `M`: `½(1 + (−1)^b M)`.
theoremprojHalf_mulVec
theorem projHalf_mulVec {d : Type*} [Fintype d] [DecidableEq d]
    (M : Matrix d d ℂ) (b : Bool) (v : d → ℂ) :
    (projHalf M b).mulVec v
      = (2⁻¹ : ℂ) • (v + (if b then (-1 : ℂ) else 1) • M.mulVec v)
theoremtensorHigh_amps_add
theorem tensorHigh_amps_add (n : Nat) (α α' β β' : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    tensorHigh n (α + α') (β + β') ψ
      = tensorHigh n α β ψ + tensorHigh n α' β' ψ
theoremtensorHigh_amps_smul
theorem tensorHigh_amps_smul (n : Nat) (c α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    tensorHigh n (c * α) (c * β) ψ = c • tensorHigh n α β ψ
theoremtBlock_branch_00
theorem tBlock_branch_00 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) false).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) false).mulVec
        (tensorHigh n 1 (phaseC (Real.pi / 4)) ψ))
      = ((2⁻¹ : ℂ) * phaseC (Real.pi / 8))
          • tensorHigh n 1 1 ((rotOf (Real.pi / 8) (axisMat n P)).mulVec ψ)
*Branch (a=0, b=0)**: joint outcome `+1`, X-destruction outcome `+1` — the data holds `e^{−iπ/8 P}ψ`, ancilla collapses to `|+⟩`, no correction.
theoremtBlock_branch_01
theorem tBlock_branch_01 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) true).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) false).mulVec
        (tensorHigh n 1 (phaseC (Real.pi / 4)) ψ))
      = ((2⁻¹ : ℂ) * phaseC (Real.pi / 8))
          • tensorHigh n 1 (-1)
              ((axisMat n P).mulVec
                ((rotOf (Real.pi / 8) (axisMat n P)).mulVec ψ))
*Branch (a=0, b=1)**: X-destruction outcome `−1` — the data holds `P·e^{−iπ/8 P}ψ` (the emitted `correct [c_b] P` fixes it), ancilla `|−⟩`.
theoremtBlock_branch_10
theorem tBlock_branch_10 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .y⟩ : PFactor)]) false).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) true).mulVec
        (tensorHigh n 1 (phaseC (Real.pi / 4)) ψ))
      = ((2⁻¹ : ℂ) * phaseC (-(Real.pi / 8)))
          • tensorHigh n 1 Complex.I
              ((rotOf (Real.pi / 8) (axisMat n P)).mulVec ψ)
*Branch (a=1, c=0)**: joint outcome `−1`, Y-destruction outcome `+1` — the data holds `e^{−iπ/8 P}ψ` directly, ancilla `|+y⟩`, no correction.
theoremtBlock_branch_11
theorem tBlock_branch_11 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .y⟩ : PFactor)]) true).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) true).mulVec
        (tensorHigh n 1 (phaseC (Real.pi / 4)) ψ))
      = (-(2⁻¹ : ℂ) * phaseC (-(Real.pi / 8)))
          • tensorHigh n 1 (-Complex.I)
              ((axisMat n P).mulVec
                ((rotOf (Real.pi / 8) (axisMat n P)).mulVec ψ))
*Branch (a=1, c=1)**: joint outcome `−1`, Y-destruction outcome `−1` — the data holds `P·e^{−iπ/8 P}ψ` (the `correct [c_b] P` fixes it), ancilla `|−y⟩`.

FormalRV.PauliRotation.Compiler.ToPPM.TBlockNeg

FormalRV/PauliRotation/Compiler/ToPPM/TBlockNeg.lean
FormalRV.PauliRotation.Compiler.ToPPM.TBlockNeg ────────────────────────────────────── *THE NEGATIVE π/8 TELEPORT-BLOCK IDENTITIES** (the `|T†⟩` chirality). Same measurement statements as the forward block, ancilla prepared as `|T†⟩` (amplitudes `(1, e^{−iπ/4})`); the data ends in `e^{+iπ/8 P}ψ` = `rotOf(−π/8)` on every branch. THE NUMERICS-CAUGHT DIFFERENCE: the Pauli correction fires on the XOR parity `c_a ^^ c_b` (not on `c_b` alone) — hence `lowerRot`'s `correct (if r.neg then [c, c+1] else [c+1])`. (0,0): ½·e^{−iπ/8} • (e^{+iπ/8P}ψ) ⊗ (1, 1) (0,1): ½·e^{−iπ/8} • (P·e^{+iπ/8P}ψ) ⊗ (1, −1) (1,0): −½·e^{+iπ/8} • (P·e^{+iπ/8P}ψ) ⊗ (1, i) (1,1): ½·e^{+iπ/8} • (e^{+iπ/8P}ψ) ⊗ (1, −i)
theoremtBlockNeg_branch_00
theorem tBlockNeg_branch_00 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) false).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) false).mulVec
        (tensorHigh n 1 (phaseC (-(Real.pi / 4))) ψ))
      = ((2⁻¹ : ℂ) * phaseC (-(Real.pi / 8)))
          • tensorHigh n 1 1
              ((rotOf (-(Real.pi / 8)) (axisMat n P)).mulVec ψ)
*Neg-block branch (a=0, b=0)**: no correction (parity 0).
theoremtBlockNeg_branch_01
theorem tBlockNeg_branch_01 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]) true).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) false).mulVec
        (tensorHigh n 1 (phaseC (-(Real.pi / 4))) ψ))
      = ((2⁻¹ : ℂ) * phaseC (-(Real.pi / 8)))
          • tensorHigh n 1 (-1)
              ((axisMat n P).mulVec
                ((rotOf (-(Real.pi / 8)) (axisMat n P)).mulVec ψ))
*Neg-block branch (a=0, b=1)**: correction `P` (parity 1).
theoremtBlockNeg_branch_10
theorem tBlockNeg_branch_10 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .y⟩ : PFactor)]) false).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) true).mulVec
        (tensorHigh n 1 (phaseC (-(Real.pi / 4))) ψ))
      = (-(2⁻¹ : ℂ) * phaseC (Real.pi / 8))
          • tensorHigh n 1 Complex.I
              ((axisMat n P).mulVec
                ((rotOf (-(Real.pi / 8)) (axisMat n P)).mulVec ψ))
*Neg-block branch (a=1, c=0)**: correction `P` (parity 1).
theoremtBlockNeg_branch_11
theorem tBlockNeg_branch_11 (n : Nat) (P : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (hk : ∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x)
    (ψ : Fin (2 ^ n) → ℂ) :
    (projHalf (axisMat (n + 1) [(⟨n, .y⟩ : PFactor)]) true).mulVec
      ((projHalf (axisMat (n + 1) (P ++ [⟨n, .z⟩])) true).mulVec
        (tensorHigh n 1 (phaseC (-(Real.pi / 4))) ψ))
      = ((2⁻¹ : ℂ) * phaseC (Real.pi / 8))
          • tensorHigh n 1 (-Complex.I)
              ((rotOf (-(Real.pi / 8)) (axisMat n P)).mulVec ψ)
*Neg-block branch (a=1, c=1)**: no correction (parity 0).

FormalRV.PauliRotation.Compiler.ToPPM.TensorHigh

FormalRV/PauliRotation/Compiler/ToPPM/TensorHigh.lean
FormalRV.PauliRotation.Compiler.ToPPM.TensorHigh ─────────────────────────────────────── THE DATA⊗ANCILLA VECTOR LAYER for the RotProg → PPM lowering. The lowering's teleport blocks act on `n` data qubits plus ONE fresh ancilla at wire `n` (the HIGH bit, under the layer's qubit-0-is-LSB convention). `tensorHigh α β ψ` is the joint state `ψ ⊗ (α|0⟩ + β|1⟩)`, and this file proves how every measurement axis the lowering emits acts on it: • data-wire `Z_q`/`X_q` singles pass through the split (`mulVec_single_z_tensorHigh`, `mulVec_single_x_tensorHigh`), • the ancilla factors act on the amplitude pair alone (`mulVec_zn_tensorHigh` : `(α,β) ↦ (α,−β)`, `mulVec_xn_tensorHigh` : `(α,β) ↦ (β,α)`, `mulVec_yn_tensorHigh` : `(α,β) ↦ (−iβ, iα)`), • a whole embedded data axis passes through (`mulVec_axis_tensorHigh`), by sorted-cons induction, • and the lowering's joint axis `P·Z_n` splits off its ancilla factor (`axisMat_snoc_zn`). Everything is entrywise over the proven `BasisAction` characterizations; no new axioms, no normalization conventions — amplitudes are explicit.
deflowBits
def lowBits (n : Nat) (m : Fin (2 ^ (n + 1))) : Fin (2 ^ n)
The data part of a joint basis index: the low `n` bits.
deftensorHigh
noncomputable def tensorHigh (n : Nat) (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    Fin (2 ^ (n + 1)) → ℂ
`ψ ⊗ (α|0⟩ + β|1⟩)` with the ancilla at the HIGH wire `n`.
theoremtensorHigh_congr
theorem tensorHigh_congr (n : Nat) {α α' β β' : ℂ}
    {ψ ψ' : Fin (2 ^ n) → ℂ} (hα : α = α') (hβ : β = β') (hψ : ψ = ψ') :
    tensorHigh n α β ψ = tensorHigh n α' β' ψ'
theoremtensorHigh_smul
theorem tensorHigh_smul (n : Nat) (c α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    tensorHigh n (c * α) (c * β) ψ = c • tensorHigh n α β ψ
Linearity facts used when assembling branches.
theoremlowBits_testBit
theorem lowBits_testBit (n : Nat) (m : Fin (2 ^ (n + 1))) (q : Nat)
    (hq : q < n) :
    ((lowBits n m : Fin (2 ^ n)) : Nat).testBit q = (m : Nat).testBit q
theoremtestBit_high_of_lt
theorem testBit_high_of_lt (n : Nat) (m : Fin (2 ^ (n + 1))) :
    (m : Nat).testBit n = decide ((m : Nat) ≥ 2 ^ n)
theoremjoint_index_eq
theorem joint_index_eq (n : Nat) (m : Fin (2 ^ (n + 1))) :
    (m : Nat) = (if (m : Nat).testBit n then 2 ^ n else 0)
      + ((lowBits n m : Fin (2 ^ n)) : Nat)
Splitting a joint index from its parts: low bits and the high bit.
theoremzMat_mulVec
theorem zMat_mulVec (n t : Nat) (ht : t < n) (v : Fin (2 ^ n) → ℂ)
    (i : Fin (2 ^ n)) :
    ((axisMat n [(⟨t, .z⟩ : PFactor)]).mulVec v) i
      = (if (i : Nat).testBit t then -1 else 1) * v i
`Z_t` acts diagonally on vectors.
theoremxMat_mulVec
theorem xMat_mulVec (n t : Nat) (ht : t < n) (v : Fin (2 ^ n) → ℂ)
    (i : Fin (2 ^ n)) :
    ((axisMat n [(⟨t, .x⟩ : PFactor)]).mulVec v) i = v (flipT n t ht i)
`X_t` acts on vectors by the bit flip.
theoremlowBits_flip
theorem lowBits_flip (n q : Nat) (hq : q < n) (m : Fin (2 ^ (n + 1))) :
    lowBits n (flipT (n + 1) q (by omega) m)
      = flipT n q hq (lowBits n m)
Low bits commute with low-wire flips.
theoremlowBits_flip_high
theorem lowBits_flip_high (n : Nat) (m : Fin (2 ^ (n + 1))) :
    lowBits n (flipT (n + 1) n (by omega) m) = lowBits n m
High-wire flip leaves the low bits alone.
theoremmulVec_zq_tensorHigh
theorem mulVec_zq_tensorHigh (n q : Nat) (hq : q < n) (α β : ℂ)
    (ψ : Fin (2 ^ n) → ℂ) :
    (axisMat (n + 1) [(⟨q, .z⟩ : PFactor)]).mulVec (tensorHigh n α β ψ)
      = tensorHigh n α β ((axisMat n [(⟨q, .z⟩ : PFactor)]).mulVec ψ)
*Data-wire `Z_q` passes through the split.**
theoremmulVec_xq_tensorHigh
theorem mulVec_xq_tensorHigh (n q : Nat) (hq : q < n) (α β : ℂ)
    (ψ : Fin (2 ^ n) → ℂ) :
    (axisMat (n + 1) [(⟨q, .x⟩ : PFactor)]).mulVec (tensorHigh n α β ψ)
      = tensorHigh n α β ((axisMat n [(⟨q, .x⟩ : PFactor)]).mulVec ψ)
*Data-wire `X_q` passes through the split.**
theoremmulVec_zn_tensorHigh
theorem mulVec_zn_tensorHigh (n : Nat) (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    (axisMat (n + 1) [(⟨n, .z⟩ : PFactor)]).mulVec (tensorHigh n α β ψ)
      = tensorHigh n α (-β) ψ
*Ancilla `Z_n` negates the `|1⟩` amplitude.**
theoremmulVec_xn_tensorHigh
theorem mulVec_xn_tensorHigh (n : Nat) (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ) :
    (axisMat (n + 1) [(⟨n, .x⟩ : PFactor)]).mulVec (tensorHigh n α β ψ)
      = tensorHigh n β α ψ
*Ancilla `X_n` swaps the amplitudes.**
theoremmulVec_axis_tensorHigh
theorem mulVec_axis_tensorHigh (n : Nat) :
    ∀ (P : PauliProduct), sortedStrict P = true →
      PauliProduct.width P ≤ n →
      (∀ f ∈ P, f.kind = PKind.z ∨ f.kind = PKind.x) →
      ∀ (α β : ℂ) (ψ : Fin (2 ^ n) → ℂ),
        (axisMat (n + 1) P).mulVec (tensorHigh n α β ψ)
          = tensorHigh n α β ((axisMat n P).mulVec ψ)
  | [], _, _, _, α, β, ψ =>
A whole SORTED data axis (all wires `< n`) passes through the split: the joint action is the data action tensored with the identity.

FormalRV.PauliRotation.Correctness.Assembly

FormalRV/PauliRotation/Correctness/Assembly.lean
FormalRV.PauliRotation.Correctness.Assembly ─────────────────────────────── D5, THE ASSEMBLY — the dictionary leg CLOSED: `seqDenote n (gateRots g) = gphase g • applyMat n g` for EVERY Gate-IR program `g` (distinct operands, within width): the compiled rotation sequence denotes the gate's Boolean semantics (`Gate.applyNat`) as a matrix, with the explicit global phase `gphase g` (a product of the per-gate constants `−i`, `e^{iπ/4}`, `−e^{−iπ/8}`). Composing with the verified scheduler (`gateRotSchedule_denote`) gives the capstone `gateRotSchedule_applyNat`: the PARALLELIZED rotation program of any arithmetic gadget means exactly the gadget's semantics — the compile → schedule → denote → applyNat chain with no specification seam.
theoremapplyMat_I
theorem applyMat_I (n : Nat) :
    applyMat n FormalRV.Framework.Gate.I = 1
defgphase
noncomputable def gphase : FormalRV.Framework.Gate → ℂ
  | .I => 1
  | .X _ => -Complex.I
  | .CX _ _ => phaseC (Real.pi / 4)
  | .CCX _ _ _ => -(phaseC (-(Real.pi / 8)))
  | .seq g₁ g₂ => gphase g₁ * gphase g₂
*The global phase of a compiled Gate program** — the product of the proven per-gate constants.
theoremapplyNat_realized
theorem applyNat_realized (n : Nat) :
    ∀ (g : FormalRV.Framework.Gate), width g ≤ n → ∀ (j : Fin (2 ^ n)),
      ∃ k : Fin (2 ^ n), ∀ b : Nat,
        Gate.applyNat g (fun c => (j : Nat).testBit c) b
          = (k : Nat).testBit b
Within width, the Boolean action of any gate on an encoded basis state is realized by an encoded basis state (agreeing at ALL bit positions).
theoremapplyMat_seq
theorem applyMat_seq (n : Nat) (g₁ g₂ : FormalRV.Framework.Gate)
    (hw₁ : width g₁ ≤ n) :
    applyMat n (.seq g₁ g₂) = applyMat n g₂ * applyMat n g₁
theoremgateRots_denote_applyNat
theorem gateRots_denote_applyNat (n : Nat) :
    ∀ (g : FormalRV.Framework.Gate), opsOK g = true → width g ≤ n →
      seqDenote n (gateRots g) = gphase g • applyMat n g
*THE DICTIONARY LEG, CLOSED**: every Gate-IR program's compiled rotation sequence denotes the gate's Boolean semantics, with the explicit global phase.
theoremgateRotSchedule_applyNat
theorem gateRotSchedule_applyNat (n : Nat) (g : FormalRV.Framework.Gate)
    (hops : opsOK g = true) (hw : width g ≤ n) :
    RotProg.denote n (gateRotSchedule g) = gphase g • applyMat n g
*THE CAPSTONE**: the PARALLELIZED rotation program of any Gate-IR gadget denotes the gadget's Boolean semantics — compile → schedule → denote → `Gate.applyNat`, no specification seam.
theoremcuccaroRot_applyNat_4
theorem cuccaroRot_applyNat_4 :
    RotProg.denote (width (cuccaro_n_bit_adder_full 4 0)) (cuccaroRot 4 0)
      = gphase (cuccaro_n_bit_adder_full 4 0)
          • applyMat _ (cuccaro_n_bit_adder_full 4 0)
*The 4-bit Cuccaro adder, FULLY semantically compiled**: its parallelized Pauli-rotation program denotes the adder's own Boolean semantics (the function `cuccaro_n_bit_adder_full_correct` is about), up to the explicit global phase.

FormalRV.PauliRotation.Correctness.CCXRow

FormalRV/PauliRotation/Correctness/CCXRow.lean
FormalRV.PauliRotation.Correctness.CCXRow ───────────────────────────── THE CCX ROW: `gateRots (CCX a b t) = H_t ; CCZ(sort₃ a b t) ; H_t` denotes the Toffoli's Boolean semantics, with explicit global phase `−e^{−iπ/8}` — combining the proven H row (`hGate_denote`, the generalized Hadamard `(Z_t+X_t)/√2`) with the proven CCZ diagonal (`ccz_rots_denote`) by a conjugation computation in the diagonal/permutation calculus of `BasisAction`. §1 `seqDenote_append` — sequences compose contravariantly. §2 `flipT` and the X-permutation collapse lemmas (`xMat_mul_apply`, `mul_xMat_apply`). §3 `applyMat_CCX` + `sort3_bits` (the sorted triple tests the same bit set). §4 **`ccx_rots_applyNat`** — the end-to-end CCX row.
theoremseqDenote_append
theorem seqDenote_append (n : Nat) (l₁ l₂ : List Rot) :
    seqDenote n (l₁ ++ l₂) = seqDenote n l₂ * seqDenote n l₁
defflipT
def flipT (n t : Nat) (ht : t < n) (i : Fin (2 ^ n)) : Fin (2 ^ n)
The bit-`t` flip as a `Fin` permutation.
theoremflipT_flipT
theorem flipT_flipT (n t : Nat) (ht : t < n) (i : Fin (2 ^ n)) :
    flipT n t ht (flipT n t ht i) = i
theoremxMat_mul_apply
theorem xMat_mul_apply (n t : Nat) (ht : t < n)
    (M : Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ) (i j : Fin (2 ^ n)) :
    (axisMat n [(⟨t, .x⟩ : PFactor)] * M) i j = M (flipT n t ht i) j
Left multiplication by `X_t` pre-flips the row index.
theoremmul_xMat_apply
theorem mul_xMat_apply (n t : Nat) (ht : t < n)
    (M : Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ) (i j : Fin (2 ^ n)) :
    (M * axisMat n [(⟨t, .x⟩ : PFactor)]) i j = M i (flipT n t ht j)
Right multiplication by `X_t` flips the column index.
theoremapplyMat_CCX
theorem applyMat_CCX (n a b t : Nat) (hat : a ≠ t) (hbt : b ≠ t) (ht : t < n)
    (i j : Fin (2 ^ n)) :
    applyMat n (.CCX a b t) i j
      = if (i : Nat) = (if (j : Nat).testBit a && (j : Nat).testBit b
            then (j : Nat) ^^^ 2 ^ t else (j : Nat))
        then 1 else 0
The CCX gate's matrix: flip bit `t` exactly when bits `a` and `b` are both set.
theoremsort3_bits
theorem sort3_bits (f : Nat → Bool) (a b t : Nat) :
    (f (sort3 a b t).1 && f (sort3 a b t).2.1 && f (sort3 a b t).2.2)
      = (f a && f b && f t)
Sorting the operand triple does not change the tested bit SET.
theoremtestBit_xor_self_bit
theorem testBit_xor_self_bit (m t : Nat) :
    (m ^^^ 2 ^ t).testBit t = !m.testBit t
The flip at `t` toggles bit `t`.
theoremhad_conj_core
theorem had_conj_core (n a b t : Nat) (hat : a ≠ t) (hbt : b ≠ t)
    (ht : t < n) :
    (axisMat n [(⟨t, .z⟩ : PFactor)] + axisMat n [(⟨t, .x⟩ : PFactor)])
        * Matrix.diagonal (fun m : Fin (2 ^ n) =>
            if (m : Nat).testBit a && (m : Nat).testBit b
                && (m : Nat).testBit t then (-1 : ℂ) else 1)
        * (axisMat n [(⟨t, .z⟩ : PFactor)] + axisMat n [(⟨t, .x⟩ : PFactor)])
      = (2 : ℂ) • applyMat n (.CCX a b t)
*THE CONJUGATION CORE**: conjugating the CCZ diagonal (stated over the unsorted operand bits) by the unnormalized Hadamard `Z_t + X_t` gives twice the Toffoli permutation.
theoremccx_rots_applyNat
theorem ccx_rots_applyNat (n a b t : Nat)
    (hab : a ≠ b) (hat : a ≠ t) (hbt : b ≠ t)
    (ha : a < n) (hb : b < n) (ht : t < n) :
    seqDenote n (gateRots (.CCX a b t))
      = (-(phaseC (-(Real.pi / 8)))) • applyMat n (.CCX a b t)
*THE CCX ROW, END-TO-END vs `Gate.applyNat`**: at any pairwise-distinct wires `a, b, t < n`, the dictionary's thirteen rotations (`H_t ; CCZ ; H_t`) denote the Toffoli's Boolean semantics as a matrix, with the explicit global phase `−e^{−iπ/8}`.

FormalRV.PauliRotation.Correctness.CCZRow

FormalRV/PauliRotation/Correctness/CCZRow.lean
FormalRV.PauliRotation.Correctness.CCZRow ───────────────────────────── THE CCZ ROW: the seven π/8 rotations of the dictionary's CCZ phase polynomial (`cczGate x y z`) denote EXACTLY the CCZ diagonal — entry `−1` precisely on basis states with all three bits set — with the explicit global phase `e^{−iπ/8}`. The derivation is fully structural, using the whole library at once: • every axis is a product of single-`Z` diagonals (`axisMat_cons_split` + `axisMat_single_z_diag`); • `rotOf` of a diagonal is a diagonal (`rotOf_diagonal`); • the seven diagonals multiply pointwise (`diagonal_mul_diagonal`); • each per-basis factor is a UNIT PHASE `e^{∓iπ/8}` and the product folds by exponent addition (`phaseC_add`) — the eight parity cases give exponent `−π/8` everywhere except the all-set case, where `7π/8 = −π/8 + π` flips the sign. This is the formal content of the `EightTToCCZScheme` phase polynomial at the matrix level.
theoremrotOf_diagonal
theorem rotOf_diagonal {N : Type*} [Fintype N] [DecidableEq N]
    (θ : ℝ) (d : N → ℂ) :
    rotOf θ (Matrix.diagonal d)
      = Matrix.diagonal (fun i =>
          (Real.cos θ : ℂ) - (Real.sin θ : ℂ) * Complex.I * d i)
`rotOf` of a diagonal matrix is the diagonal of pointwise rotations.
theoremaxisMat_cons_split
theorem axisMat_cons_split (n : Nat) (f : PFactor) (P : PauliProduct)
    (hs : sortedStrict (f :: P) = true) :
    axisMat n (f :: P) = axisMat n [f] * axisMat n P
A sorted axis splits off its head factor multiplicatively.
defzsgn
noncomputable def zsgn (q : Nat) (m : Fin (2 ^ n)) : ℂ
The single-`Z` sign at a wire.
theoremaxisMat_zz_diag
theorem axisMat_zz_diag (n x y : Nat) (hxy : x < y) (hy : y < n) :
    axisMat n [(⟨x, .z⟩ : PFactor), ⟨y, .z⟩]
      = Matrix.diagonal (fun m => zsgn x m * zsgn y m)
The `ZZ` pair axis is the product diagonal.
theoremaxisMat_zzz_diag
theorem axisMat_zzz_diag (n x y z : Nat) (hxy : x < y) (hyz : y < z)
    (hz : z < n) :
    axisMat n [(⟨x, .z⟩ : PFactor), ⟨y, .z⟩, ⟨z, .z⟩]
      = Matrix.diagonal (fun m => zsgn x m * (zsgn y m * zsgn z m))
The `ZZZ` triple axis is the product diagonal.
theoremphase_factor_pos
theorem phase_factor_pos (θ : ℝ) :
    (Real.cos θ : ℂ) - (Real.sin θ : ℂ) * Complex.I * 1 = phaseC (-θ)
theoremphase_factor_neg
theorem phase_factor_neg (θ : ℝ) :
    (Real.cos θ : ℂ) - (Real.sin θ : ℂ) * Complex.I * (-1) = phaseC θ
theoremneg_one_eq_phaseC_pi
theorem neg_one_eq_phaseC_pi : (-1 : ℂ) = phaseC Real.pi
`−1` as the phase `e^{iπ}`.
defcczMat
noncomputable def cczMat (n x y z : Nat) :
    Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
*The CCZ diagonal**: `−1` exactly on the all-three-bits-set states.
theoremccz_rots_denote
theorem ccz_rots_denote (n x y z : Nat) (hxy : x < y) (hyz : y < z)
    (hz : z < n) :
    seqDenote n ((cczGate x y z).flatten)
      = phaseC (-(Real.pi / 8)) • cczMat n x y z
*THE CCZ ROW**: the dictionary's seven π/8 rotations denote the CCZ diagonal, with the explicit global phase `e^{−iπ/8}` — the matrix-level content of the seven-rotation phase polynomial.

FormalRV.PauliRotation.Correctness.CircuitIdentities

FormalRV/PauliRotation/Correctness/CircuitIdentities.lean
FormalRV.PauliRotation.Correctness.CircuitIdentities ──────────────────────────────────────── THE REUSABLE CIRCUIT-IDENTITY LIBRARY of the semantic core (John's directive: standard identities proven ONCE, abstractly, so every gate-row proof becomes a short structural derivation instead of an entrywise computation). Everything is stated over ABSTRACT matrices `M N : Matrix m m ℂ` with the involution / anticommutation hypotheses (`M² = 1`, `MN = −NM`) — the only facts Pauli axes actually provide — so each identity instantiates at 2×2 Paulis AND at `axisMat n P` for any width and wires: §1 Angle-doubling rows: `T² = S`, `S² = Z-level`, `(π/2)² = π`. §2 THE PUSH RULE (`rot_quarter_push`): a π/4 rotation moves past ANY rotation about an anticommuting axis by conjugating the axis, `N ↦ (−i)·MN` — the Litinski commutation rule at matrix level. §3 THE BRAID (`rot_braid`): for anticommuting involutions, `M_{π/4} · N_{π/4} · M_{π/4} = (−i) · (M+N)/√2` — the generalized Hadamard, DERIVED from push + merge (no entry computations). §4 Instantiations: `dict_H_from_braid` re-derives `Dictionary.dict_H` structurally; `axisMat_anticomm` upgrades the sign theorem to the anticommuting case; `hGate_denote` gives THE n-QUBIT H ROW — the dictionary's three rotations at ANY wire `q < n` denote the generalized Hadamard about `(X_q + Z_q)/√2`.
theoremrot_eighth_sq
theorem rot_eighth_sq {M : Matrix m m ℂ} (hM : M * M = 1) :
    rotOf (Real.pi / 8) M * rotOf (Real.pi / 8) M = rotOf (Real.pi / 4) M
Two T-level rotations make an S-level rotation.
theoremrot_quarter_sq
theorem rot_quarter_sq {M : Matrix m m ℂ} (hM : M * M = 1) :
    rotOf (Real.pi / 4) M * rotOf (Real.pi / 4) M = rotOf (Real.pi / 2) M
Two S-level rotations make a Pauli-level rotation.
theoremrot_half_sq
theorem rot_half_sq {M : Matrix m m ℂ} (hM : M * M = 1) :
    rotOf (Real.pi / 2) M * rotOf (Real.pi / 2) M = -1
Two Pauli-level rotations make the global phase `−1`.
theoremconj_anticomm
theorem conj_anticomm {M N : Matrix m m ℂ} (hM : M * M = 1)
    (hMN : M * N = -(N * M)) : M * N * M = -N
`M·N·M = −N` for an involution `M` anticommuting with `N` — the workhorse conjugation fact.
theoremconj_axis_invol
theorem conj_axis_invol {M N : Matrix m m ℂ} (hM : M * M = 1)
    (hN : N * N = 1) (hMN : M * N = -(N * M)) :
    ((-Complex.I) • (M * N)) * ((-Complex.I) • (M * N)) = 1
The conjugated axis `(−i)·MN` is again an involution.
theoremrot_quarter_push
theorem rot_quarter_push {M N : Matrix m m ℂ} (hM : M * M = 1)
    (hMN : M * N = -(N * M)) (φ : ℝ) :
    rotOf (Real.pi / 4) M * rotOf φ N
      = rotOf φ ((-Complex.I) • (M * N)) * rotOf (Real.pi / 4) M
*THE PUSH RULE**: a π/4 rotation about `M` moves past a rotation about an anticommuting axis `N` (ANY angle) by conjugating the axis to `(−i)·MN` — the Litinski commutation rule at the matrix level.
theoremrot_braid
theorem rot_braid {M N : Matrix m m ℂ} (hM : M * M = 1)
    (hMN : M * N = -(N * M)) :
    rotOf (Real.pi / 4) M * rotOf (Real.pi / 4) N * rotOf (Real.pi / 4) M
      = (-Complex.I) • ((((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ) • (M + N))
*THE BRAID IDENTITY**: for anticommuting involutions, `M_{π/4} · N_{π/4} · M_{π/4} = (−i) • (M + N)/√2` — the generalized Hadamard, derived structurally: push, merge the two `M`-rotations to a Pauli, expand the conjugated quarter-rotation. No entry computations.
theorempauliZX_anticomm
theorem pauliZX_anticomm :
    Pauli.toMatrix .Z * Pauli.toMatrix .X
      = -(Pauli.toMatrix .X * Pauli.toMatrix .Z)
The 2×2 anticommutation `Z·X = −X·Z`, from the proven sign table.
theoremhMat_eq_sum
theorem hMat_eq_sum :
    hMat = (((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ)
      • (Pauli.toMatrix .X + Pauli.toMatrix .Z)
The Hadamard is the normalized anticommuting sum `(X + Z)/√2`.
theoremdict_H_from_braid
theorem dict_H_from_braid :
    rotOf (Real.pi / 4) (Pauli.toMatrix .Z)
        * rotOf (Real.pi / 4) (Pauli.toMatrix .X)
        * rotOf (Real.pi / 4) (Pauli.toMatrix .Z)
      = (-Complex.I) • hMat
*`dict_H`, re-derived structurally from the braid** — the same theorem as `Dictionary.dict_H`, now a three-line corollary of the reusable identity instead of an entrywise computation.
theoremaxisMat_anticomm
theorem axisMat_anticomm (n : Nat) {P Q : PauliProduct}
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (h : acCount P Q % 2 = 1) :
    axisMat n P * axisMat n Q = -(axisMat n Q * axisMat n P)
*Anticommutation bridge**: an ODD anticommuting-overlap count makes the axis matrices anticommute (the odd twin of `axisMat_comm_of_commF`).
theoremacCount_ZX_self
theorem acCount_ZX_self (q : Nat) :
    acCount [(⟨q, .z⟩ : PFactor)] [(⟨q, .x⟩ : PFactor)] = 1
The single-qubit Z/X axes at the same wire anticommute syntactically.
theoremhGate_denote
theorem hGate_denote (n q : Nat) (hq : q + 1 ≤ n) :
    seqDenote n ((hGate q).flatten)
      = (-Complex.I) • ((((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ)
          • (axisMat n [⟨q, .z⟩] + axisMat n [⟨q, .x⟩]))
*THE n-QUBIT H ROW**: at ANY wire `q < n`, the dictionary's three π/4 rotations (`hGate q`) denote the generalized Hadamard about `(X_q + Z_q)/√2`, with the explicit global phase `−i` — obtained by instantiating the braid at the axis matrices. This is the first full n-qubit row of the dictionary leg.

FormalRV.PauliRotation.Correctness.GateRows

FormalRV/PauliRotation/Correctness/GateRows.lean
FormalRV.PauliRotation.Correctness.GateRows ─────────────────────────────── THE n-QUBIT GATE ROWS of the dictionary leg, built from the reusable identity library (`CircuitIdentities.lean`) — each row a structural derivation, no entrywise n-qubit computations: §1 `opsMat_mul_pointwise` / `axisMat_mk2_split` — DISJOINT-SUPPORT MULTIPLICATIVITY: the axis matrix of a multi-qubit product is the product of its single-qubit axis matrices. This reduces EVERY multi-qubit axis the Gate dictionary emits (Z_cX_t, Z_aZ_b, …) to single-qubit ones. §2 `rot_controlled_pauli` — THE CONTROLLED-PAULI IDENTITY (abstract): for commuting involutions `A`, `B`, `B_{−π/4} · A_{−π/4} · (AB)_{π/4} = e^{iπ/4} · ½(1 + A + B − AB)` — the projector form of a controlled gate (`½(1+A)` selects the `A = +1` sector where nothing happens; `½(1−A)` applies `B`). §3 `cnot_rots_denote` — **THE n-QUBIT CX ROW**: at any distinct wires `c, t < n`, the dictionary's three rotations denote `e^{iπ/4} · ½(1 + Z_c + X_t − Z_cX_t)` — the controlled-X in operator (projector) form, with the explicit global phase. Remaining for the full assembly (next tranche): the single-qubit basis-action lemmas (Z_q = bit-parity diagonal, X_q = bit flip), which convert these operator forms into `Gate.applyNat` permutation matrices, and the CCZ row (seven commuting Z-type diagonals, phase polynomial from `EightTToCCZScheme`).
defmulP
def mulP (f g : Nat → Pauli) (k : Nat) : Pauli
Pointwise product of two qubit assignments with disjoint supports.
theoremopsMat_mul_pointwise
theorem opsMat_mul_pointwise (n : Nat) (f g : Nat → Pauli)
    (h : ∀ k, f k = .I ∨ g k = .I) :
    opsMat n f * opsMat n g = opsMat n (mulP f g)
*Disjoint-support multiplicativity**: when at every qubit at least one factor is the identity, the Kronecker interpretations multiply pointwise.
theoremkindFn_single
theorem kindFn_single (q : Nat) (k : PKind) (i : Nat) :
    kindFn [(⟨q, k⟩ : PFactor)] i
      = if q = i then pkindToBQ k else Pauli.I
The qubit assignment of a one-factor axis.
theoremkindFn_pair
theorem kindFn_pair (a b : PFactor) (i : Nat) :
    kindFn [a, b] i
      = if a.qubit = i then pkindToBQ a.kind
        else if b.qubit = i then pkindToBQ b.kind else Pauli.I
The qubit assignment of a two-factor axis.
theorempkindToBQ_ne_I
theorem pkindToBQ_ne_I (k : PKind) : pkindToBQ k ≠ Pauli.I
`pkindToBQ` never produces the identity.
theoremaxisMat_mk2_split
theorem axisMat_mk2_split (n c t : Nat) (kc kt : PKind) (hct : c ≠ t) :
    axisMat n (mk2 c kc t kt)
      = axisMat n [⟨c, kc⟩] * axisMat n [⟨t, kt⟩]
*The two-qubit axis splits**: the axis matrix of the sorted pair `mk2` is the product of the two single-qubit axis matrices (either index order).
theoremcommF_singles_disjoint
theorem commF_singles_disjoint (c t : Nat) (kc kt : PKind) (h : t ≠ c) :
    commF [(⟨c, kc⟩ : PFactor)] [(⟨t, kt⟩ : PFactor)] = true
Disjoint single-qubit axes commute syntactically.
theoremrot_controlled_pauli
theorem rot_controlled_pauli {A B : Matrix m m ℂ}
    (hA : A * A = 1) (hB : B * B = 1) (hAB : A * B = B * A) :
    rotOf (-(Real.pi / 4)) B * rotOf (-(Real.pi / 4)) A
        * rotOf (Real.pi / 4) (A * B)
      = phaseC (Real.pi / 4) • ((2 : ℂ)⁻¹ • (1 + A + B - A * B))
*THE CONTROLLED-PAULI IDENTITY**: for commuting involutions `A`, `B`, the dictionary's three signed π/4 rotations compose to the projector form of the controlled gate — `½(1+A)` (the `A = +1` sector) acts as identity, `½(1−A)` applies `B` — with the explicit global phase `e^{iπ/4}`.
theoremcnot_rots_denote
theorem cnot_rots_denote (n c t : Nat) (hct : c ≠ t) (hc : c + 1 ≤ n) :
    seqDenote n (gateRots (.CX c t))
      = phaseC (Real.pi / 4) •
          ((2 : ℂ)⁻¹ • (1 + axisMat n [⟨c, .z⟩] + axisMat n [⟨t, .x⟩]
            - axisMat n [⟨c, .z⟩] * axisMat n [⟨t, .x⟩]))
*THE n-QUBIT CX ROW**: at any distinct wires `c, t < n`, the dictionary's three rotations (`cnotGate c t`) denote the controlled-X in projector form, `e^{iπ/4} · ½(1 + Z_c + X_t − Z_cX_t)` — by splitting the two-qubit axis and instantiating the controlled-Pauli identity at the axis matrices. No entrywise computation.

FormalRV.PauliRotation.Correctness.QFTRows

FormalRV/PauliRotation/Correctness/QFTRows.lean
FormalRV.PauliRotation.Correctness.QFTRows ────────────────────────────── THE QFT-SIDE GATE ROW: the banded inverse QFT's kept ladder gate — the controlled-S† on adjacent wires — has its semantic row proven by the CCZ recipe (three commuting Z-type diagonals folding by phase-exponent addition): `seqDenote n (csDagRots t) = e^{iπ/8} • csDagMat n t` where `csDagMat` is the controlled-S† diagonal (`−i` exactly on the both-bits-set states). With this row, EVERY constituent of the compiled banded IQFT / QPE has proven semantics: H (`hGate_denote`), CS† (here), the bit-reversal SWAPs' CNOTs (`cnot_rots_applyNat`), and the modular-exponentiation oracle (`gateRotSchedule_applyNat`, since the oracle is Gate-IR). HONEST BOUNDARY (unchanged, by design): the exact QFT is NOT expressible at the four discrete angles — only the banded circuit compiles, and the dropped `m ≥ 2` tail carries the error budget already derived in `QFT/AQFTCompile.lean`. Assembling these operator rows into a single `uc_eval`/`IQFT_matrix`-facing statement is the BaseUCom bridge, a separate (unstarted) leg.
defcsDagMat
noncomputable def csDagMat (n t : Nat) :
    Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
*The controlled-S† diagonal** on wires `(t, t+1)`: `−i` exactly when both bits are set.
theoremcsDag_rots_denote
theorem csDag_rots_denote (n t : Nat) (ht : t + 1 < n) :
    seqDenote n (csDagRots t) = phaseC (Real.pi / 8) • csDagMat n t
*THE CS† ROW**: the banded IQFT's kept ladder gate — three π/8 rotations — denotes the controlled-S† diagonal, with the explicit global phase `e^{iπ/8}`.

FormalRV.PauliRotation.Correctness.ShorEndToEnd

FormalRV/PauliRotation/Correctness/ShorEndToEnd.lean
FormalRV.PauliRotation.Correctness.ShorEndToEnd ─────────────────────────────────── THE COMPOSITION: all the proven gadget rows assemble into an end-to-end semantic statement for the Pauli-rotation compilation of the Shor/QPE circuit shape H-layer ; modexp oracle ; banded inverse QFT Every block reduces to its CLOSED operator form: • the H-layer to a product of generalized Hadamards (`hLayer_denote`, from `hGate_denote`), • the IQFT ladder to a product of Hadamards and controlled-S† diagonals (`ladderLow_denote`, from `csDag_rots_denote`), • the bit-reversal cascade to CX permutation products (`swapRots_denote`/`bitRev_denote`, from `cnot_rots_applyNat`), • the Gate-IR modexp oracle to its own Boolean semantics (`gateRots_denote_applyNat`), and `shorQPE_rots_denote` multiplies them out with ONE explicit global phase — composed end-to-end semantics for the whole compiled algorithm, with `shorQPE_schedule_denote` extending it through the verified parallelizer and `shor15_schedule_denote` instantiating it at the verified Shor-15 modexp oracle. HONEST SCOPE: the oracle enters as the QPE black box on the same wire pool (the repo's own QPE design — the controlled-powers wiring is the QPE-side contract); relating the closed operator form to `IQFT_matrix`/`uc_eval` is the BaseUCom bridge (unstarted); the banding ε is the existing derived budget in `QFT/AQFTCompile`.
defhadSum
noncomputable def hadSum (n q : Nat) : Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
The UNNORMALIZED Hadamard at wire `q` (`Z_q + X_q`); the `√2/2` and the `−i` live in the phases, keeping every block matrix scalar-free.
defhLayerMat
noncomputable def hLayerMat (n : Nat) : Nat → Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
  | 0 => 1
  | k + 1 => hadSum n k * hLayerMat n k
The H-layer product `(Z+X)_{k−1} ⋯ (Z+X)_0`.
theoremhLayer_denote
theorem hLayer_denote (n : Nat) :
    ∀ k, k ≤ n →
      seqDenote n (hLayerRots k)
        = ((-Complex.I) * (((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ)) ^ k
            • hLayerMat n k
defladderMat
noncomputable def ladderMat (n : Nat) : Nat → Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
  | 0 => 1
  | t + 1 => ladderMat n t * hadSum n t * csDagMat n t
The ladder product for targets `t−1 … 0`: each target contributes a Hadamard then (reading right-to-left) its kept controlled-S† diagonal.
theoremladderLow_denote
theorem ladderLow_denote (n : Nat) :
    ∀ t, t < n →
      seqDenote n (aqftLadderLow t)
        = ((-Complex.I) * (((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ)
            * phaseC (Real.pi / 8)) ^ t • ladderMat n t
theoremswapRots_denote
theorem swapRots_denote (n i j : Nat) (hij : i ≠ j) (hi : i < n) (hj : j < n) :
    seqDenote n (swapRots i j)
      = phaseC (Real.pi / 4) ^ 3
          • (applyMat n (.CX i j) * applyMat n (.CX j i)
              * applyMat n (.CX i j))
One SWAP, semantically: three CX permutations with phase `e^{i3π/4}`.
defbitRevMat
noncomputable def bitRevMat (n k : Nat) : Nat → Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
  | 0 => 1
  | i + 1 => (applyMat n (.CX i (k - 1 - i)) * applyMat n (.CX (k - 1 - i) i)
      * applyMat n (.CX i (k - 1 - i))) * bitRevMat n k i
The bit-reversal product over the first `m` pairs of width `k`.
theorembitRev_denote
theorem bitRev_denote (n k : Nat) (hk : k ≤ n) :
    seqDenote n (bitRevRots k)
      = (phaseC (Real.pi / 4) ^ 3) ^ (k / 2) • bitRevMat n k (k / 2)
defiqftMat
noncomputable def iqftMat (n k : Nat) : Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
The closed operator form of the banded inverse QFT on `k+1` wires.
defiqftPhase
noncomputable def iqftPhase (k : Nat) : ℂ
The banded IQFT's global phase.
theoremaqft2_denote
theorem aqft2_denote (n k : Nat) (hk : k + 1 ≤ n) :
    seqDenote n (aqft2Rots (k + 1)) = iqftPhase k • iqftMat n k
*The banded IQFT block, semantically.**
theoremshorQPE_rots_denote
theorem shorQPE_rots_denote (n k : Nat) (oracleG : FormalRV.Framework.Gate)
    (hops : opsOK oracleG = true) (hw : FormalRV.Resource.width oracleG ≤ n)
    (hk : k + 1 ≤ n) :
    seqDenote n (qpeRots (k + 1) (gateRots oracleG))
      = (iqftPhase k * gphase oracleG
            * ((-Complex.I) * (((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ)) ^ (k + 1))
          • (iqftMat n k * applyMat n oracleG * hLayerMat n (k + 1))
*END-TO-END SEMANTICS OF THE COMPILED SHOR/QPE CIRCUIT SHAPE**: the full rotation sequence — H-layer, then any Gate-IR modular-exponentiation oracle, then the banded inverse QFT — denotes the product of the three blocks' closed operator forms, with ONE explicit global phase.
theoremshorQPE_schedule_denote
theorem shorQPE_schedule_denote (n k : Nat) (oracleG : FormalRV.Framework.Gate)
    (hops : opsOK oracleG = true) (hw : FormalRV.Resource.width oracleG ≤ n)
    (hk : k + 1 ≤ n)
    (hb : ∀ r ∈ qpeRots (k + 1) (gateRots oracleG),
        sortedStrict r.axis = true ∧ PauliProduct.width r.axis ≤ n) :
    RotProg.denote n (qpeSchedule (k + 1) (gateRots oracleG))
      = (iqftPhase k * gphase oracleG
            * ((-Complex.I) * (((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ)) ^ (k + 1))
          • (iqftMat n k * applyMat n oracleG * hLayerMat n (k + 1))
*…and through the verified parallelizer**: the SCHEDULED program means the same thing (side condition decidable per instance).
theoremshor15_schedule_denote
theorem shor15_schedule_denote :
    RotProg.denote 7 (qpeSchedule 3 (gateRots (shorModExpVerified 1 15 7 13)))
      = (iqftPhase 2 * gphase (shorModExpVerified 1 15 7 13)
            * ((-Complex.I) * (((Real.sqrt 2 : ℝ) / 2 : ℝ) : ℂ)) ^ 3)
          • (iqftMat 7 2 * applyMat 7 (shorModExpVerified 1 15 7 13)
              * hLayerMat 7 3)
*Shor-15, compiled and parallelized, end to end**: with the verified in-place modexp oracle at `(N, a, ainv) = (15, 7, 13)` and three phase qubits, the scheduled Pauli-rotation program of the whole QPE circuit denotes the composed closed form — all side conditions kernel-checked.

FormalRV.PauliRotation.Correctness.SingleQubitRows

FormalRV/PauliRotation/Correctness/SingleQubitRows.lean
FormalRV.PauliRotation.Correctness.SingleQubitRows ────────────────────────────────────────────────── The SINGLE-QUBIT rows of the gate dictionary, proven at the 2x2 level (each with its EXPLICIT global phase `phaseC θ`): Z-axis : rotOf θ Z = diag(e^{−iθ}, e^{iθ}) (generic θ) T row : rotOf (π/8) Z = e^{−iπ/8} • diag(1, e^{iπ/4}) S row : rotOf (π/4) Z = e^{−iπ/4} • diag(1, i) Z/X rows : rotOf (π/2) P = (−i) • P (rotOf_pi_div_two) H row : Z_{π/4}·X_{π/4}·Z_{π/4} = e^{−iπ/4} • H These are exactly the 2×2 facts the n-qubit lift consumes; the lift itself lives in `GateRows`/`CCZRow`/`CCXRow` and assembles in `Assembly` (`gateRots_denote_applyNat`) — the dictionary leg is CLOSED.
defphaseC
noncomputable def phaseC (θ : ℝ) : ℂ
`e^{iθ}` (the global phases the dictionary tracks explicitly).
theoremphaseC_eq
theorem phaseC_eq (θ : ℝ) :
    phaseC θ = (Real.cos θ : ℂ) + (Real.sin θ : ℂ) * Complex.I
theoremphaseC_add
theorem phaseC_add (a b : ℝ) : phaseC a * phaseC b = phaseC (a + b)
theoremrotZ_eq_diag
theorem rotZ_eq_diag (θ : ℝ) :
    rotOf θ (Pauli.toMatrix .Z) = !![phaseC (-θ), 0; 0, phaseC θ]
*Generic Z-row**: a Z-rotation by ANY angle is the diagonal phase pair `diag(e^{−iθ}, e^{iθ})`.
theoremdict_T
theorem dict_T :
    rotOf (Real.pi / 8) (Pauli.toMatrix .Z)
      = phaseC (-(Real.pi / 8)) • !![1, 0; 0, phaseC (Real.pi / 4)]
*The T row**: the π/8 Z-rotation IS the T gate, up to the explicit global phase `e^{−iπ/8}`.
theoremdict_S
theorem dict_S :
    rotOf (Real.pi / 4) (Pauli.toMatrix .Z)
      = phaseC (-(Real.pi / 4)) • !![1, 0; 0, Complex.I]
*The S row**: the π/4 Z-rotation IS the S gate, up to `e^{−iπ/4}`.
defhMat
noncomputable def hMat : Matrix (Fin 2) (Fin 2) ℂ
The Hadamard matrix.
theoremdict_H
theorem dict_H :
    rotOf (Real.pi / 4) (Pauli.toMatrix .Z)
        * rotOf (Real.pi / 4) (Pauli.toMatrix .X)
        * rotOf (Real.pi / 4) (Pauli.toMatrix .Z)
      = (-Complex.I) • hMat
*The H row**: the dictionary's `Z_{π/4} · X_{π/4} · Z_{π/4}` IS the Hadamard, up to the explicit global phase `−i = e^{−iπ/2}` — the keystone single-qubit fact for compiling H (and hence CCX = H·CCZ·H). (NB the phase: the first draft claimed `e^{−iπ/4}` and the entrywise proof REFUTED it — the dictionary leg is exactly the kind of fact that must be proven, not asserted.)

FormalRV.PauliRotation.Examples

FormalRV/PauliRotation/Examples.lean
FormalRV.PauliRotation.Examples ─────────────────────────────── Worked examples of PARALLEL Pauli rotations expressed SYNTACTICALLY: a `RotLayer` is a list of rotations whose axes pairwise commute (`RotLayer.wf` checks this by the structural test `commF`), and a well-formed layer is ONE unit of parallel logical depth. Every claim below closes by `decide` on the concrete syntax tree — a skeptic can `#eval` `RotLayer.wf` / `depth` / `countPi8` on any of these programs without reading a proof. HONESTY: these anchors witness SYNTACTIC parallelism (pairwise commutation) plus the counters. The `commF` ⇒ matrix-commutation bridge they once waited on is PROVEN (CommBridge.lean `axisMat_comm_of_commF`, `Rot.denote_swap`); Scheduler.lean carries it to the verified ASAP parallelizer (`scheduleList_denote`), and PushRules.lean to the Litinski anticommuting push.
deftransversalT4
def transversalT4 : RotProg
example(example)
example : RotProg.wf transversalT4 = true
example(example)
example : rotDepth transversalT4 = 1
example(example)
example : countPi8 transversalT4 = 4
example(example)
example : RotProg.width transversalT4 = 4
defxxzzLayer
def xxzzLayer : RotProg
example(example)
example : RotProg.wf xxzzLayer = true
example(example)
example : rotDepth xxzzLayer = 1
defcnotLayer
def cnotLayer (c t : Nat) : RotProg
example(example)
example : RotProg.wf (cnotLayer 0 1) = true
example(example)
example : rotDepth (cnotLayer 0 1) = 1
example(example)
example : rotDepth (cnotGate 0 1) = 3
deftwoCnotLayer
def twoCnotLayer : RotProg
example(example)
example : RotProg.wf twoCnotLayer = true
example(example)
example : rotDepth twoCnotLayer = 1
example(example)
example : RotProg.wf (cczLayer 0 1 2) = true
example(example)
example : rotDepth (cczLayer 0 1 2) = 1
example(example)
example : countPi8 (cczLayer 0 1 2) = 7
example(example)
example : RotLayer.wf
    [⟨false, .piEighth, [⟨0, .x⟩]⟩, ⟨false, .piEighth, [⟨0, .z⟩]⟩] = false
example(example)
example : RotProg.wf
    [[⟨false, .piEighth, [⟨0, .x⟩]⟩], [⟨false, .piEighth, [⟨0, .z⟩]⟩]] = true
The same two rotations ARE expressible sequentially (two layers).
defmixedProg
def mixedProg : RotProg
example(example)
example : RotProg.wf mixedProg = true
example(example)
example : rotDepth mixedProg = 3
example(example)
example : countPi8 mixedProg = 2
example(example)
example : countRot mixedProg = 5

FormalRV.PauliRotation.Gadgets

FormalRV/PauliRotation/Gadgets.lean
FormalRV.PauliRotation.Gadgets — umbrella. ALL existing arithmetic gadget families, compiled to Pauli rotations through the verified pipeline (`GateBridge.lean`), ONE FILE PER FAMILY: • `Gadgets/CuccaroAdder.lean` — n-bit adder + const-arithmetic variants • `Gadgets/GidneyAdder.lean` — faithful / patched Gidney ripple adders • `Gadgets/ModularAdderCuccaro.lean` — THE LIVE (x+c) mod N + controlled form • `Gadgets/ModularAdderGidney.lean` — the standalone Gidney mod-add pipeline • `Gadgets/ModMult.lean` — const multiplier + in-place MCP oracle • `Gadgets/ModExp.lean` — Shor mod-exp chains (verified-oracle + counting model) • `Gadgets/UnaryLookup.lean` — faithful QROM + Gray-code read • `Gadgets/Windowed.lean` — windowed mul, mod-N, in-place weld, Gray-code Uniform shape per gadget: `<g>Rot` (the parallelized rotation program), `<g>Rot_countPi8` (SYMBOLIC rotation T-count, composing the family's existing anchored `tcount` theorem), and where small, an anchored `gateRotSchedule_denote` correctness instance with `decide` side conditions.
(no documented top-level declarations)

FormalRV.PauliRotation.Gadgets.CuccaroAdder

FormalRV/PauliRotation/Gadgets/CuccaroAdder.lean
FormalRV.PauliRotation.Gadgets.CuccaroAdder ─────────────────────────────────────────── THE CUCCARO–DKM RIPPLE-CARRY FAMILY, compiled to Pauli rotations through the verified pipeline (`GateBridge.lean`): the n-bit adder and its constant-arithmetic variants (add-const, sub-const, compare, the mod-reduce halves). Every gadget gets the uniform pair: • SYMBOLIC rotation T-count (all sizes/placements), by composing the generic `gateRotSchedule_countPi8 : countPi8 = Gate.tcount` with the family's existing anchored `tcount_*` theorem; • the optimizer-leg CORRECTNESS instance at a small concrete size (`gateRotSchedule_denote`, side conditions kernel-checked by `decide`). HONESTY: "correctness" = the parallel layers denote exactly the naive gate-by-gate rotation sequence; the dictionary leg (sequence = Gate unitary up to global phase) is the layer's known open item (`PauliRotation/README.md`).
defcuccaroRot
def cuccaroRot (bits q_start : Nat) : RotProg
The Cuccaro adder as a parallelized rotation program.
theoremcuccaroRot_countPi8
theorem cuccaroRot_countPi8 (bits q_start : Nat) :
    countPi8 (cuccaroRot bits q_start) = 14 * bits
*Rotation T-count = `14·bits`**, all sizes and placements.
theoremcuccaroRot_denote_4
theorem cuccaroRot_denote_4 :
    RotProg.denote (width (cuccaro_n_bit_adder_full 4 0)) (cuccaroRot 4 0)
      = seqDenote _ (gateRots (cuccaro_n_bit_adder_full 4 0))
Correctness instance (4-bit adder on its own 9 qubits).
example(example)
example : RotProg.wf (cuccaroRot 2 0) = true
example(example)
example : (gateRots (cuccaro_n_bit_adder_full 2 0)).length = 76
example(example)
example : rotDepth (cuccaroRot 2 0) = 20
defcuccaroAddConstRot
def cuccaroAddConstRot (bits q_start c : Nat) : RotProg
`target += c` as a parallelized rotation program.
theoremcuccaroAddConstRot_countPi8
theorem cuccaroAddConstRot_countPi8 (bits q_start c : Nat) :
    countPi8 (cuccaroAddConstRot bits q_start c) = 14 * bits
theoremcuccaroAddConstRot_denote_3
theorem cuccaroAddConstRot_denote_3 :
    RotProg.denote (width (cuccaro_addConstGate 3 0 5))
        (cuccaroAddConstRot 3 0 5)
      = seqDenote _ (gateRots (cuccaro_addConstGate 3 0 5))
defcuccaroSubConstRot
def cuccaroSubConstRot (bits q_start N : Nat) : RotProg
`target -= N` (two's-complement add) as a rotation program.
theoremcuccaroSubConstRot_countPi8
theorem cuccaroSubConstRot_countPi8 (bits q_start N : Nat) :
    countPi8 (cuccaroSubConstRot bits q_start N) = 14 * bits
defcuccaroCompareRot
def cuccaroCompareRot (bits q_start N : Nat) : RotProg
Constant comparison (forward MAJ chain only; flag at the top carry).
theoremcuccaroCompareRot_countPi8
theorem cuccaroCompareRot_countPi8 (bits q_start N : Nat) :
    countPi8 (cuccaroCompareRot bits q_start N) = 7 * bits
defcuccaroSubForwardRot
def cuccaroSubForwardRot (bits q_start N : Nat) : RotProg
Forward-only subtract half (mod-reduce building block).
theoremcuccaroSubForwardRot_countPi8
theorem cuccaroSubForwardRot_countPi8 (bits q_start N : Nat) :
    countPi8 (cuccaroSubForwardRot bits q_start N) = 7 * bits
defcuccaroSubReverseRot
def cuccaroSubReverseRot (bits q_start N : Nat) : RotProg
Reverse-only subtract half (mod-reduce building block).
theoremcuccaroSubReverseRot_countPi8
theorem cuccaroSubReverseRot_countPi8 (bits q_start N : Nat) :
    countPi8 (cuccaroSubReverseRot bits q_start N) = 7 * bits

FormalRV.PauliRotation.Gadgets.GidneyAdder

FormalRV/PauliRotation/Gadgets/GidneyAdder.lean
FormalRV.PauliRotation.Gadgets.GidneyAdder ────────────────────────────────────────── THE (PATCHED) GIDNEY RIPPLE-CARRY ADDER, compiled to Pauli rotations (`GateBridge.lean`): the canonical faithful no-measurement adder (`gidney_adder`, T-count `14·(n+2)`), the carry-clean PATCHED variant the modular-adder layer builds on, and the forward-faithful reverse-patched composition (`7·(n+2)`). HONESTY: the COST-ONLY skeleton gates of `RippleCarryAdderCostSkeleton.lean` are deliberately NOT compiled here — they have the right T-count but the wrong carry logic (their own header says so); only the faithful gadgets get rotation programs. Correctness = the optimizer leg (see `PauliRotation/README.md`).
defgidneyRot
def gidneyRot (n : Nat) : RotProg
The faithful no-measurement Gidney adder as a rotation program.
theoremgidneyRot_countPi8
theorem gidneyRot_countPi8 (n : Nat) :
    countPi8 (gidneyRot (n + 2)) = 14 * (n + 2)
*Rotation T-count = `14·(n+2)`** (the family's `n ≥ 2` shape).
theoremgidneyRot_denote_2
theorem gidneyRot_denote_2 :
    RotProg.denote (width (gidney_adder 2)) (gidneyRot 2)
      = seqDenote _ (gateRots (gidney_adder 2))
Correctness instance (the 2-bit faithful adder).
defgidneyPatchedRot
def gidneyPatchedRot (n : Nat) : RotProg
The patched (carry-clearing) adder as a rotation program.
theoremgidneyPatchedRot_countPi8
theorem gidneyPatchedRot_countPi8 (n : Nat) :
    countPi8 (gidneyPatchedRot (n + 2)) = 14 * (n + 2)
theoremgidneyPatchedRot_denote_2
theorem gidneyPatchedRot_denote_2 :
    RotProg.denote (width (gidney_adder_full_faithful_no_measurement_patched 2))
        (gidneyPatchedRot 2)
      = seqDenote _ (gateRots (gidney_adder_full_faithful_no_measurement_patched 2))
defgidneyForwardRevRot
def gidneyForwardRevRot (n : Nat) : RotProg
The forward + patched-reverse composition as a rotation program.
theoremgidneyForwardRevRot_countPi8
theorem gidneyForwardRevRot_countPi8 (n : Nat) :
    countPi8 (gidneyForwardRevRot (n + 2)) = 7 * (n + 2)

FormalRV.PauliRotation.Gadgets.ModExp

FormalRV/PauliRotation/Gadgets/ModExp.lean
FormalRV.PauliRotation.Gadgets.ModExp ───────────────────────────────────── MODULAR EXPONENTIATION (Shor's order-finding oracle layer), compiled to Pauli rotations (`GateBridge.lean`): • `shorModExpVerified` — the chain of `2·bits` VERIFIED in-place MCP multipliers (each step is the term the verified Shor theorem uses); rotation T-count `224·bits³`. • `shorModExp` — the out-of-place COUNTING-MODEL chain; `112·bits³`. HONESTY (inherited from the family's own headers, restated here): the chains have EXACT per-term T-counts, but the chain-computes-`a^x mod N` theorem is NOT proven (count-only/scaffolded); `shorModExp` additionally has no feedback (counting model only). The rotation programs below are faithful compilations of THOSE terms — no more, no less.
defshorModExpVerifiedRot
def shorModExpVerifiedRot (bits N a ainv : Nat) : RotProg
The `2·bits`-fold chain of verified in-place MCP multipliers as a rotation program.
theoremshorModExpVerifiedRot_countPi8
theorem shorModExpVerifiedRot_countPi8 (bits N a ainv : Nat)
    (hcop : Nat.Coprime a N) (hcopinv : Nat.Coprime ainv N)
    (hpos : 0 < ainv) (hlt : ainv < N) (hodd : Odd N) (h1 : 1 < N) :
    countPi8 (shorModExpVerifiedRot bits N a ainv) = 224 * bits ^ 3
*Rotation T-count = `224·bits³`** for valid Shor parameters.
theoremshorModExpVerifiedRot_denote_1
theorem shorModExpVerifiedRot_denote_1 :
    RotProg.denote (width (shorModExpVerified 1 15 7 13))
        (shorModExpVerifiedRot 1 15 7 13)
      = seqDenote _ (gateRots (shorModExpVerified 1 15 7 13))
Correctness instance at 1-bit Shor-15 parameters (kept small: the side-condition `decide` walks the whole gate term).
example(example)
example : countPi8 (shorModExpVerifiedRot 2 15 7 13) = 1792
defshorModExpRot
def shorModExpRot (bits N a : Nat) : RotProg
The out-of-place counting-model chain as a rotation program (⚠ counting model: not a valid mod-exp; see header).
theoremshorModExpRot_countPi8
theorem shorModExpRot_countPi8 (bits N a : Nat)
    (hcop : Nat.Coprime a N) (hodd : Odd N) (h1 : 1 < N) :
    countPi8 (shorModExpRot bits N a) = 112 * bits ^ 3
*Rotation T-count = `112·bits³`** for any valid Shor base.

FormalRV.PauliRotation.Gadgets.ModMult

FormalRV/PauliRotation/Gadgets/ModMult.lean
FormalRV.PauliRotation.Gadgets.ModMult ────────────────────────────────────── THE MODULAR MULTIPLIER — the shift-and-accumulate constant multiplier and THE in-place MCP multiplier (`modmult_MCP_gate`, the verified Shor oracle building block) — compiled to Pauli rotations (`GateBridge.lean`). The T-count theorems inherit the family's number-theoretic hypotheses (`Coprime`, `Odd N`, `1 < N`, …): exactly the hypotheses under which the source `tcount` theorems hold (no step constant degenerates to 0).
defmodMultConstRot
def modMultConstRot (bits N a : Nat) : RotProg
The shift-and-accumulate constant multiplier as a rotation program.
theoremmodMultConstRot_countPi8
theorem modMultConstRot_countPi8 (bits N a : Nat)
    (hcop : Nat.Coprime a N) (hodd : Odd N) (h1 : 1 < N) :
    countPi8 (modMultConstRot bits N a) = 56 * bits ^ 2
*Rotation T-count = `56·bits²`** for any valid Shor base (`gcd(a,N) = 1`, `N` odd, `N > 1`).
theoremmodMultConstRot_denote_2_15_7
theorem modMultConstRot_denote_2_15_7 :
    RotProg.denote (width (modmult_const_gate 2 15 7)) (modMultConstRot 2 15 7)
      = seqDenote _ (gateRots (modmult_const_gate 2 15 7))
Correctness instance: the 108-gate `x ↦ 7·x mod 15` multiplier (the README's worked example) parallelizes soundly.
defmodMultMCPRot
def modMultMCPRot (bits N a ainv : Nat) : RotProg
The in-place MCP modular multiplier as a rotation program.
theoremmodMultMCPRot_countPi8
theorem modMultMCPRot_countPi8 (bits N a ainv : Nat)
    (hcop : Nat.Coprime a N) (hcopinv : Nat.Coprime ainv N)
    (hpos : 0 < ainv) (hlt : ainv < N) (hodd : Odd N) (h1 : 1 < N) :
    countPi8 (modMultMCPRot bits N a ainv) = 112 * bits ^ 2
*Rotation T-count = `112·bits²`** for valid Shor parameters — the rotation-level restatement of the family's `modmult_tcount`, about EXACTLY the gate term the verified `modmult_correct` is about.
theoremmodMultMCPRot_denote_2_15
theorem modMultMCPRot_denote_2_15 :
    RotProg.denote (width (modmult_MCP_gate 2 15 7 13)) (modMultMCPRot 2 15 7 13)
      = seqDenote _ (gateRots (modmult_MCP_gate 2 15 7 13))
Correctness instance at the Shor-15 parameters (`a = 7`, `ainv = 13`).
example(example)
example : countPi8 (modMultMCPRot 2 15 7 13) = 448

FormalRV.PauliRotation.Gadgets.ModularAdderCuccaro

FormalRV/PauliRotation/Gadgets/ModularAdderCuccaro.lean
FormalRV.PauliRotation.Gadgets.ModularAdderCuccaro ────────────────────────────────────────────────── THE LIVE MODULAR ADDER — the Cuccaro/SQIR-style `(x + c) mod N` and its controlled form (`sqir_style_controlledModAddConst_gate` is the per-bit primitive the verified multiplier and Shor actually stack) — compiled to Pauli rotations (`GateBridge.lean`). T-counts carry the family's honest `if c = 0` dispatch (the `c = 0` case is the identity, zero rotations).
defcuccaroModAddRot
def cuccaroModAddRot (bits N c : Nat) : RotProg
The clean Cuccaro-style modular adder as a rotation program.
theoremcuccaroModAddRot_countPi8
theorem cuccaroModAddRot_countPi8 (bits N c : Nat) :
    countPi8 (cuccaroModAddRot bits N c)
      = if c = 0 then 0 else 56 * bits
*Rotation T-count = `56·bits`** (`0` when `c = 0`), all sizes.
theoremcuccaroModAddRot_denote_3
theorem cuccaroModAddRot_denote_3 :
    RotProg.denote (width (sqir_style_modAddConst_clean_gate 3 5 2))
        (cuccaroModAddRot 3 5 2)
      = seqDenote _ (gateRots (sqir_style_modAddConst_clean_gate 3 5 2))
Correctness instance (3 bits, `(x + 2) mod 5`).
defcuccaroCtrlModAddRot
def cuccaroCtrlModAddRot (bits q_start N c controlIdx flagPos : Nat) : RotProg
The controlled Cuccaro-style modular adder as a rotation program.
theoremcuccaroCtrlModAddRot_countPi8
theorem cuccaroCtrlModAddRot_countPi8
    (bits q_start N c controlIdx flagPos : Nat) :
    countPi8 (cuccaroCtrlModAddRot bits q_start N c controlIdx flagPos)
      = if c = 0 then 0 else 56 * bits
*Rotation T-count = `56·bits`** (`0` when `c = 0`) — the per-bit cost whose `bits`-fold forward+uncompute stack is ModMult's `112·bits²`.

FormalRV.PauliRotation.Gadgets.ModularAdderGidney

FormalRV/PauliRotation/Gadgets/ModularAdderGidney.lean
FormalRV.PauliRotation.Gadgets.ModularAdderGidney ───────────────────────────────────────────────── THE GIDNEY-PIPELINE MODULAR ADDER family — `(x + c) mod N` built on the patched Gidney adder (verified but STANDALONE; the live Shor path uses the Cuccaro pipeline, `ModularAdderCuccaro.lean`) — compiled to Pauli rotations (`GateBridge.lean`): the constant add/sub primitives, the flag-conditional add, and the full clean + controlled modular adders. Count shapes follow the family's `bits = n + 2` / `n + 1` statements.
defgidneyAddConstRot
def gidneyAddConstRot (bits c : Nat) : RotProg
`target += c` as a rotation program.
theoremgidneyAddConstRot_countPi8
theorem gidneyAddConstRot_countPi8 (n c : Nat) :
    countPi8 (gidneyAddConstRot (n + 2) c) = 14 * (n + 2)
theoremgidneyAddConstRot_denote_2
theorem gidneyAddConstRot_denote_2 :
    RotProg.denote (width (addConstGate 2 1)) (gidneyAddConstRot 2 1)
      = seqDenote _ (gateRots (addConstGate 2 1))
defgidneySubConstRot
def gidneySubConstRot (bits N : Nat) : RotProg
`target -= N` (two's complement) as a rotation program.
theoremgidneySubConstRot_countPi8
theorem gidneySubConstRot_countPi8 (n N : Nat) :
    countPi8 (gidneySubConstRot (n + 2) N) = 14 * (n + 2)
defgidneyCondAddRot
def gidneyCondAddRot (bits N flagIdx : Nat) : RotProg
The flag-conditional constant add as a rotation program.
theoremgidneyCondAddRot_countPi8
theorem gidneyCondAddRot_countPi8 (n N flagIdx : Nat) :
    countPi8 (gidneyCondAddRot (n + 2) N flagIdx) = 14 * (n + 2)
defgidneyModAddRot
def gidneyModAddRot (bits N c : Nat) : RotProg
The clean `(x + c) mod N` as a rotation program.
theoremgidneyModAddRot_countPi8
theorem gidneyModAddRot_countPi8 (n N c : Nat) :
    countPi8 (gidneyModAddRot (n + 1) N c) = 70 * (n + 2)
*Rotation T-count = `70·(n+2)`** for `bits = n + 1` (the family's five-adder pipeline shape).
defgidneyCtrlModAddRot
def gidneyCtrlModAddRot (bits N c controlIdx flagIdx : Nat) : RotProg
The controlled `(x + c) mod N` as a rotation program.
theoremgidneyCtrlModAddRot_countPi8
theorem gidneyCtrlModAddRot_countPi8 (n N c controlIdx flagIdx : Nat) :
    countPi8 (gidneyCtrlModAddRot (n + 1) N c controlIdx flagIdx)
      = 70 * (n + 2) + 14
*Rotation T-count = `70·(n+2) + 14`** for `bits = n + 1`.

FormalRV.PauliRotation.Gadgets.SemanticInstances

FormalRV/PauliRotation/Gadgets/SemanticInstances.lean
FormalRV.PauliRotation.Gadgets.SemanticInstances ──────────────────────────────────────────────── EVERY GADGET, SEMANTICALLY COMPILED: per-gadget instances of the capstone `gateRotSchedule_applyNat` — for each compiled rotation program in `Gadgets/`, the PARALLELIZED Pauli-rotation program denotes the gadget's own Boolean semantics (`Gate.applyNat`), up to the explicit global phase `gphase`. Side conditions (`opsOK` operand distinctness, width) are kernel-checked by `decide` at the anchored sizes; the statements use the gadget's own `width` so no bound is ever guessed. Together with the per-family files this completes, for EVERY existing arithmetic gadget: compilation, exact symbolic T-counts, parallelization soundness, and end-to-end semantic correctness. (`cuccaroRot_applyNat_4`, the n-bit adder instance, lives in `Assembly.lean` as the exemplar.)
theoremcuccaroAddConstRot_applyNat
theorem cuccaroAddConstRot_applyNat :
    RotProg.denote (Resource.width (cuccaro_addConstGate 3 0 5)) (cuccaroAddConstRot 3 0 5)
      = gphase (cuccaro_addConstGate 3 0 5)
          • applyMat _ (cuccaro_addConstGate 3 0 5)
theoremcuccaroSubConstRot_applyNat
theorem cuccaroSubConstRot_applyNat :
    RotProg.denote (Resource.width (cuccaro_subConstGate 3 0 5)) (cuccaroSubConstRot 3 0 5)
      = gphase (cuccaro_subConstGate 3 0 5)
          • applyMat _ (cuccaro_subConstGate 3 0 5)
theoremcuccaroCompareRot_applyNat
theorem cuccaroCompareRot_applyNat :
    RotProg.denote (Resource.width (cuccaro_compareConstForwardGate 3 0 5))
        (cuccaroCompareRot 3 0 5)
      = gphase (cuccaro_compareConstForwardGate 3 0 5)
          • applyMat _ (cuccaro_compareConstForwardGate 3 0 5)
theoremcuccaroSubForwardRot_applyNat
theorem cuccaroSubForwardRot_applyNat :
    RotProg.denote (Resource.width (cuccaro_subConstForwardOnlyGate 3 0 5))
        (cuccaroSubForwardRot 3 0 5)
      = gphase (cuccaro_subConstForwardOnlyGate 3 0 5)
          • applyMat _ (cuccaro_subConstForwardOnlyGate 3 0 5)
theoremcuccaroSubReverseRot_applyNat
theorem cuccaroSubReverseRot_applyNat :
    RotProg.denote (Resource.width (cuccaro_subConstReverseOnlyGate 3 0 5))
        (cuccaroSubReverseRot 3 0 5)
      = gphase (cuccaro_subConstReverseOnlyGate 3 0 5)
          • applyMat _ (cuccaro_subConstReverseOnlyGate 3 0 5)
theoremgidneyRot_applyNat
theorem gidneyRot_applyNat :
    RotProg.denote (Resource.width (gidney_adder 2)) (gidneyRot 2)
      = gphase (gidney_adder 2) • applyMat _ (gidney_adder 2)
theoremgidneyPatchedRot_applyNat
theorem gidneyPatchedRot_applyNat :
    RotProg.denote (Resource.width (gidney_adder_full_faithful_no_measurement_patched 2))
        (gidneyPatchedRot 2)
      = gphase (gidney_adder_full_faithful_no_measurement_patched 2)
          • applyMat _ (gidney_adder_full_faithful_no_measurement_patched 2)
theoremgidneyForwardRevRot_applyNat
theorem gidneyForwardRevRot_applyNat :
    RotProg.denote (Resource.width (gidney_adder_forward_faithful_full_reverse_patched 2))
        (gidneyForwardRevRot 2)
      = gphase (gidney_adder_forward_faithful_full_reverse_patched 2)
          • applyMat _ (gidney_adder_forward_faithful_full_reverse_patched 2)
theoremcuccaroModAddRot_applyNat
theorem cuccaroModAddRot_applyNat :
    RotProg.denote (Resource.width (sqir_style_modAddConst_clean_gate 3 5 2))
        (cuccaroModAddRot 3 5 2)
      = gphase (sqir_style_modAddConst_clean_gate 3 5 2)
          • applyMat _ (sqir_style_modAddConst_clean_gate 3 5 2)
theoremcuccaroCtrlModAddRot_applyNat
theorem cuccaroCtrlModAddRot_applyNat :
    RotProg.denote (Resource.width (sqir_style_controlledModAddConst_gate 3 2 5 2 1 0))
        (cuccaroCtrlModAddRot 3 2 5 2 1 0)
      = gphase (sqir_style_controlledModAddConst_gate 3 2 5 2 1 0)
          • applyMat _ (sqir_style_controlledModAddConst_gate 3 2 5 2 1 0)
theoremgidneyAddConstRot_applyNat
theorem gidneyAddConstRot_applyNat :
    RotProg.denote (Resource.width (addConstGate 2 1)) (gidneyAddConstRot 2 1)
      = gphase (addConstGate 2 1) • applyMat _ (addConstGate 2 1)
theoremgidneySubConstRot_applyNat
theorem gidneySubConstRot_applyNat :
    RotProg.denote (Resource.width (subConstGate 2 1)) (gidneySubConstRot 2 1)
      = gphase (subConstGate 2 1) • applyMat _ (subConstGate 2 1)
theoremgidneyCondAddRot_applyNat
theorem gidneyCondAddRot_applyNat :
    RotProg.denote (Resource.width (conditionalAddConstGate 2 1 8))
        (gidneyCondAddRot 2 1 8)
      = gphase (conditionalAddConstGate 2 1 8)
          • applyMat _ (conditionalAddConstGate 2 1 8)
theoremgidneyModAddRot_applyNat
theorem gidneyModAddRot_applyNat :
    RotProg.denote (Resource.width (modAddConstGate 2 3 1)) (gidneyModAddRot 2 3 1)
      = gphase (modAddConstGate 2 3 1) • applyMat _ (modAddConstGate 2 3 1)
theoremgidneyCtrlModAddRot_applyNat
theorem gidneyCtrlModAddRot_applyNat :
    RotProg.denote (Resource.width (controlledModAddConstGate 2 3 1 9 10))
        (gidneyCtrlModAddRot 2 3 1 9 10)
      = gphase (controlledModAddConstGate 2 3 1 9 10)
          • applyMat _ (controlledModAddConstGate 2 3 1 9 10)
theoremmodMultConstRot_applyNat
theorem modMultConstRot_applyNat :
    RotProg.denote (Resource.width (modmult_const_gate 2 15 7)) (modMultConstRot 2 15 7)
      = gphase (modmult_const_gate 2 15 7)
          • applyMat _ (modmult_const_gate 2 15 7)
theoremmodMultMCPRot_applyNat
theorem modMultMCPRot_applyNat :
    RotProg.denote (Resource.width (modmult_MCP_gate 2 15 7 13)) (modMultMCPRot 2 15 7 13)
      = gphase (modmult_MCP_gate 2 15 7 13)
          • applyMat _ (modmult_MCP_gate 2 15 7 13)
theoremshorModExpVerifiedRot_applyNat
theorem shorModExpVerifiedRot_applyNat :
    RotProg.denote (Resource.width (shorModExpVerified 1 15 7 13))
        (shorModExpVerifiedRot 1 15 7 13)
      = gphase (shorModExpVerified 1 15 7 13)
          • applyMat _ (shorModExpVerified 1 15 7 13)
theoremshorModExpRot_applyNat
theorem shorModExpRot_applyNat :
    RotProg.denote (Resource.width (shorModExp 1 15 7)) (shorModExpRot 1 15 7)
      = gphase (shorModExp 1 15 7) • applyMat _ (shorModExp 1 15 7)
theoremunaryLookupRot_applyNat
theorem unaryLookupRot_applyNat :
    RotProg.denote (Resource.width (unary_lookup_multi_iteration 2 [([0], [5])]))
        (unaryLookupRot 2 [([0], [5])])
      = gphase (unary_lookup_multi_iteration 2 [([0], [5])])
          • applyMat _ (unary_lookup_multi_iteration 2 [([0], [5])])
theoremgrayLookupRot_applyNat
theorem grayLookupRot_applyNat :
    RotProg.denote (Resource.width (grayLookupReadAt 2 (fun i => 6 + i) 1 (fun _ => 1)))
        (grayLookupRot 2 (fun i => 6 + i) 1 (fun _ => 1))
      = gphase (grayLookupReadAt 2 (fun i => 6 + i) 1 (fun _ => 1))
          • applyMat _ (grayLookupReadAt 2 (fun i => 6 + i) 1 (fun _ => 1))
theoremwindowedMulRot_applyNat
theorem windowedMulRot_applyNat :
    RotProg.denote (Resource.width (windowedMulCircuit 2 4 3 2)) (windowedMulRot 2 4 3 2)
      = gphase (windowedMulCircuit 2 4 3 2)
          • applyMat _ (windowedMulCircuit 2 4 3 2)
theoremwindowedModNMulRot_applyNat
theorem windowedModNMulRot_applyNat :
    RotProg.denote (Resource.width (windowedModNMulCircuit 2 4 3 7 2))
        (windowedModNMulRot 2 4 3 7 2)
      = gphase (windowedModNMulCircuit 2 4 3 7 2)
          • applyMat _ (windowedModNMulCircuit 2 4 3 7 2)
theoremwindowedModNInPlaceRot_applyNat
theorem windowedModNInPlaceRot_applyNat :
    RotProg.denote (Resource.width (windowedModNMulGate 2 4 7 2 3 5))
        (windowedModNInPlaceRot 2 4 7 2 3 5)
      = gphase (windowedModNMulGate 2 4 7 2 3 5)
          • applyMat _ (windowedModNMulGate 2 4 7 2 3 5)
theoremgrayWindowedMulRot_applyNat
theorem grayWindowedMulRot_applyNat :
    RotProg.denote (Resource.width (grayWindowedMulCircuitOf cuccaroAdder 2 4 3 2))
        (grayWindowedMulRot 2 4 3 2)
      = gphase (grayWindowedMulCircuitOf cuccaroAdder 2 4 3 2)
          • applyMat _ (grayWindowedMulCircuitOf cuccaroAdder 2 4 3 2)

FormalRV.PauliRotation.Gadgets.UnaryLookup

FormalRV/PauliRotation/Gadgets/UnaryLookup.lean
FormalRV.PauliRotation.Gadgets.UnaryLookup ────────────────────────────────────────── THE BABBUSH-STYLE QROM LOOKUPS, compiled to Pauli rotations (`GateBridge.lean`): • `unary_lookup_multi_iteration` — the faithful unary-iteration lookup (per-address prefix-AND compute/uncompute): `14·n_addr` T per iteration, `14·n_addr·|iters|` total; • `grayLookupReadAt` — the Gray-code/sawtooth read: `14·(2^w − 1)` T, the factor-`w` saving over the faithful read (selection contract proven identical in `UnaryLookupGrayCode.lean`). Both compile exactly (Toffoli-class). NB the Gray-code module lives in namespace `FormalRV.Shor.WindowedCircuit`, not `BQAlgo`.
defunaryLookupRot
def unaryLookupRot (n_addr : Nat) (iters : List (List Nat × List Nat)) : RotProg
The faithful multi-iteration QROM lookup as a rotation program.
theoremunaryLookupRot_countPi8
theorem unaryLookupRot_countPi8 (n_addr : Nat)
    (iters : List (List Nat × List Nat)) :
    countPi8 (unaryLookupRot n_addr iters) = 14 * n_addr * iters.length
*Rotation T-count = `14·n_addr·|iters|`** — the faithful (no measurement, no Gray-code) QROM cost, for every table.
defgrayLookupRot
def grayLookupRot (w : Nat) (pos : Nat → Nat) (W : Nat) (T : Nat → Nat) : RotProg
The Gray-code QROM read as a rotation program.
theoremgrayLookupRot_countPi8
theorem grayLookupRot_countPi8 (w : Nat) (pos : Nat → Nat) (W : Nat)
    (T : Nat → Nat) :
    countPi8 (grayLookupRot w pos W T) = 14 * (2 ^ w - 1)
*Rotation T-count = `14·(2^w − 1)`** — the Gray-code saving, for every window size, position map, and table.

FormalRV.PauliRotation.Gadgets.Windowed

FormalRV/PauliRotation/Gadgets/Windowed.lean
FormalRV.PauliRotation.Gadgets.Windowed ─────────────────────────────────────── THE WINDOWED ARITHMETIC (Gidney–Ekerå windows), compiled to Pauli rotations (`GateBridge.lean`): • `windowedMulCircuit` — the (Cuccaro-instance) windowed multiplier: `numWin·(28·w·2^w + 14·bits)` T; • `windowedModNMulCircuit` — the per-window mod-N multiplier: `numWin·(56·w·2^w + 56·bits)` T; • `windowedModNMulGate` — the IN-PLACE mod-N Shor-weld entry: `2·numWin·(56·w·2^w + 56·bits)` T; • `grayWindowedMulCircuitOf cuccaroAdder` — the Gray-code windowed multiplier: `numWin·(28·(2^w − 1) + 14·bits)` T (the `w` factor gone). All compile exactly. This file only IMPORTS the windowed modules (the folder belongs to another work lane) and the rotation T-counts compose with their existing anchored `tcount_*` theorems symbolically.
defwindowedMulRot
def windowedMulRot (w bits a numWin : Nat) : RotProg
The windowed multiplier as a rotation program.
theoremwindowedMulRot_countPi8
theorem windowedMulRot_countPi8 (w bits a numWin : Nat) :
    countPi8 (windowedMulRot w bits a numWin)
      = numWin * (28 * w * 2 ^ w + 14 * bits)
*Rotation T-count = `numWin·(28·w·2^w + 14·bits)`**, all parameters.
defwindowedModNMulRot
def windowedModNMulRot (w bits a N numWin : Nat) : RotProg
The exactly-modular per-window multiplier as a rotation program.
theoremwindowedModNMulRot_countPi8
theorem windowedModNMulRot_countPi8 (w bits a N numWin : Nat) :
    countPi8 (windowedModNMulRot w bits a N numWin)
      = numWin * (56 * w * 2 ^ w + 56 * bits)
*Rotation T-count = `numWin·(56·w·2^w + 56·bits)`**, all parameters.
defwindowedModNInPlaceRot
def windowedModNInPlaceRot (w bits N numWin c cinv : Nat) : RotProg
The in-place mod-N windowed multiplier (Shor-weld wrapper) as a rotation program.
theoremwindowedModNInPlaceRot_countPi8
theorem windowedModNInPlaceRot_countPi8 (w bits N numWin c cinv : Nat) :
    countPi8 (windowedModNInPlaceRot w bits N numWin c cinv)
      = 2 * numWin * (56 * w * 2 ^ w + 56 * bits)
*Rotation T-count = `2·numWin·(56·w·2^w + 56·bits)`** (the in-place forward + inverse-uncompute factor), all parameters.
defgrayWindowedMulRot
def grayWindowedMulRot (w bits a numWin : Nat) : RotProg
The Gray-code windowed multiplier (over the Cuccaro `Adder` instance) as a rotation program.
theoremgrayWindowedMulRot_countPi8
theorem grayWindowedMulRot_countPi8 (w bits a numWin : Nat) :
    countPi8 (grayWindowedMulRot w bits a numWin)
      = numWin * (28 * (2 ^ w - 1) + 14 * bits)
*Rotation T-count = `numWin·(28·(2^w − 1) + 14·bits)`** — the Gray-code window cost with the `w` factor gone, all parameters.
theoremwindowedMulRot_denote_2_4_3_2
theorem windowedMulRot_denote_2_4_3_2 :
    RotProg.denote (Resource.width (windowedMulCircuit 2 4 3 2))
        (windowedMulRot 2 4 3 2)
      = seqDenote _ (gateRots (windowedMulCircuit 2 4 3 2))
Correctness instance (`w = 2`, `bits = 4`, `a = 3`, two windows).

FormalRV.PauliRotation.Semantics.BasisAction

FormalRV/PauliRotation/Semantics/BasisAction.lean
FormalRV.PauliRotation.Semantics.BasisAction ────────────────────────────────── D1, THE BASIS-ACTION CORE: what the axis matrices DO to computational basis states, in bit arithmetic — the lemmas that convert the operator forms of `GateRows.lean` into `Gate.applyNat` permutation matrices. Index convention (pinned by `finProdFinEquiv (i₁, i₂) = i₂ + 2·i₁`): qubit 0 is the LEAST-SIGNIFICANT BIT; basis state `j : Fin (2^n)` assigns qubit `k` the bit `(j : Nat).testBit k`. §1 `opsMat_one`, `opsMat_succ_apply` — the entry-level recursion. §2 Index bridges: bits and XOR through the Kronecker pair split. §3 **`axisMat_single_z_apply`** — `Z_q` is the bit-parity diagonal: entry `(i,j) = [i = j] · (−1)^{bit q of j}`. *`axisMat_single_x_apply`** — `X_q` is the bit-flip permutation: entry `(i,j) = [i = j XOR 2^q]`. §4 `applyMat` — `Gate.applyNat` as a permutation matrix — and *`xGate_rots_applyNat`: THE FIRST END-TO-END ROW** against the repo's Boolean gate semantics: the dictionary's X-rotation denotes `(−i) · applyMat n (X q)`.
theoremopsMat_one
theorem opsMat_one (n : Nat) : opsMat n (fun _ => Pauli.I) = 1
theoremopsMat_succ_apply
theorem opsMat_succ_apply (n : Nat) (f : Nat → Pauli)
    (i₁ j₁ : Fin (2 ^ n)) (i₂ j₂ : Fin 2) :
    opsMat (n + 1) f (finProdFinEquiv (i₁, i₂)) (finProdFinEquiv (j₁, j₂))
      = opsMat n (fun i => f (i + 1)) i₁ j₁ * (f 0).toMatrix i₂ j₂
theoremval_coe
theorem val_coe {n : Nat} (x : Fin (2 ^ n * 2)) :
    @Fin.val (2 ^ (n + 1)) x = @Fin.val (2 ^ n * 2) x
`Fin.val` is type-ascription-blind across the defeq `2^(n+1) = 2^n·2` (the recurring trap of this development, made explicit once).
theorempair_val
theorem pair_val {n : Nat} (i₁ : Fin (2 ^ n)) (i₂ : Fin 2) :
    ((finProdFinEquiv (i₁, i₂) : Fin (2 ^ n * 2)) : Nat)
      = (i₂ : Nat) + 2 * (i₁ : Nat)
theorempair_testBit_zero
theorem pair_testBit_zero {n : Nat} (i₁ : Fin (2 ^ n)) (i₂ : Fin 2) :
    ((finProdFinEquiv (i₁, i₂) : Fin (2 ^ n * 2)) : Nat).testBit 0
      = decide ((i₂ : Nat) = 1)
theorempair_testBit_succ
theorem pair_testBit_succ {n : Nat} (i₁ : Fin (2 ^ n)) (i₂ : Fin 2) (k : Nat) :
    ((finProdFinEquiv (i₁, i₂) : Fin (2 ^ n * 2)) : Nat).testBit (k + 1)
      = (i₁ : Nat).testBit k
theoremxor_one_split
theorem xor_one_split (a b : Nat) (hb : b < 2) :
    (b + 2 * a) ^^^ 1 = (1 - b) + 2 * a
XOR with `1` on the 2-adic split flips the low component.
theoremxor_pow_succ_split
theorem xor_pow_succ_split (a b : Nat) (hb : b < 2) (q : Nat) :
    (b + 2 * a) ^^^ 2 ^ (q + 1) = b + 2 * (a ^^^ 2 ^ q)
XOR with `2^(q+1)` on the 2-adic split acts on the high component.
theoremopsMat_single_z
private theorem opsMat_single_z (n : Nat) :
    ∀ (q : Nat), q < n → ∀ (i j : Fin (2 ^ n)),
      opsMat n (fun k => if q = k then Pauli.Z else Pauli.I) i j
        = if (i : Nat) = (j : Nat)
          then (if (j : Nat).testBit q then -1 else 1) else 0
theoremopsMat_single_x
private theorem opsMat_single_x (n : Nat) :
    ∀ (q : Nat), q < n → ∀ (i j : Fin (2 ^ n)),
      opsMat n (fun k => if q = k then Pauli.X else Pauli.I) i j
        = if (i : Nat) = (j : Nat) ^^^ 2 ^ q then 1 else 0
theoremaxisMat_single_z_apply
theorem axisMat_single_z_apply (n q : Nat) (hq : q < n) (i j : Fin (2 ^ n)) :
    axisMat n [(⟨q, .z⟩ : PFactor)] i j
      = if (i : Nat) = (j : Nat)
        then (if (j : Nat).testBit q then -1 else 1) else 0
*`Z_q` is the bit-parity diagonal.**
theoremaxisMat_single_x_apply
theorem axisMat_single_x_apply (n q : Nat) (hq : q < n) (i j : Fin (2 ^ n)) :
    axisMat n [(⟨q, .x⟩ : PFactor)] i j
      = if (i : Nat) = (j : Nat) ^^^ 2 ^ q then 1 else 0
*`X_q` is the bit-flip permutation.**
defapplyMat
noncomputable def applyMat (n : Nat) (g : FormalRV.Framework.Gate) :
    Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
*The repo's Boolean gate semantics as a permutation matrix** at width `n` (basis state `j` assigns qubit `k` the bit `testBit k`).
theoremapplyMat_X
theorem applyMat_X (n q : Nat) (hq : q < n) (i j : Fin (2 ^ n)) :
    applyMat n (.X q) i j
      = if (i : Nat) = (j : Nat) ^^^ 2 ^ q then 1 else 0
The X gate's matrix is the bit-flip permutation.
theoremxGate_rots_applyNat
theorem xGate_rots_applyNat (n q : Nat) (hq : q < n) :
    seqDenote n (gateRots (.X q)) = (-Complex.I) • applyMat n (.X q)
*THE FIRST END-TO-END ROW vs `Gate.applyNat`**: at any wire `q < n`, the dictionary's X-rotation denotes the gate's Boolean semantics as a matrix, with the explicit global phase `−i`.
theoremaxisMat_single_z_diag
theorem axisMat_single_z_diag (n c : Nat) (hc : c < n) :
    axisMat n [(⟨c, .z⟩ : PFactor)]
      = Matrix.diagonal (fun k : Fin (2 ^ n) =>
          if (k : Nat).testBit c then (-1 : ℂ) else 1)
`Z_c` in `Matrix.diagonal` form (products collapse against it).
theoremtestBit_xor_other
theorem testBit_xor_other {c t : Nat} (hct : c ≠ t) (m : Nat) :
    (m ^^^ 2 ^ t).testBit c = m.testBit c
Flipping bit `t` preserves any other bit `c`.
theoremxor_two_pow_ne
theorem xor_two_pow_ne (m t : Nat) : m ^^^ 2 ^ t ≠ m
Flipping bit `t` moves the state: `m XOR 2^t ≠ m`.
theoremapplyMat_CX
theorem applyMat_CX (n c t : Nat) (hct : c ≠ t) (ht : t < n)
    (i j : Fin (2 ^ n)) :
    applyMat n (.CX c t) i j
      = if (i : Nat) = (if (j : Nat).testBit c
            then (j : Nat) ^^^ 2 ^ t else (j : Nat))
        then 1 else 0
The CX gate's matrix: flip bit `t` exactly when bit `c` is set.
theoremcnot_rots_applyNat
theorem cnot_rots_applyNat (n c t : Nat) (hct : c ≠ t) (hc : c < n)
    (ht : t < n) :
    seqDenote n (gateRots (.CX c t))
      = phaseC (Real.pi / 4) • applyMat n (.CX c t)
*THE CX ROW, END-TO-END vs `Gate.applyNat`**: at any distinct wires `c, t < n`, the dictionary's three rotations denote the CNOT's Boolean semantics as a matrix, with the explicit global phase `e^{iπ/4}`.
theoremopsMat_single_y
private theorem opsMat_single_y (n : Nat) :
    ∀ (q : Nat), q < n → ∀ (i j : Fin (2 ^ n)),
      opsMat n (fun k => if q = k then Pauli.Y else Pauli.I) i j
        = if (i : Nat) = (j : Nat) ^^^ 2 ^ q
          then (if (j : Nat).testBit q then -Complex.I else Complex.I)
          else 0
theoremaxisMat_single_y_apply
theorem axisMat_single_y_apply (n q : Nat) (hq : q < n) (i j : Fin (2 ^ n)) :
    axisMat n [(⟨q, .y⟩ : PFactor)] i j
      = if (i : Nat) = (j : Nat) ^^^ 2 ^ q
        then (if (j : Nat).testBit q then -Complex.I else Complex.I)
        else 0
*Y_q is the bit-flip permutation with the +-i phases.**

FormalRV.PauliRotation.Semantics.CommBridge

FormalRV/PauliRotation/Semantics/CommBridge.lean
FormalRV.PauliRotation.Semantics.CommBridge ───────────────────────────────── THE COMMUTATION BRIDGE — closing the layer's known gap 1: `commF P Q = true → axisMat n P * axisMat n Q = axisMat n Q * axisMat n P` i.e. the SYNTACTIC commutation test (even anticommuting-overlap count, kernel-decidable) implies MATRIX commutation of the axes. This is the exchange engine every reorder/parallelization transform rests on: combined with the proven `rotOf_comm`, it yields the program-level exchange lemma `Rot.denote_swap` (adjacent rotations with `commF`-commuting axes swap without changing the denotation). Proof route (all mechanical): §1 single-qubit: `p·q = ±q·p` with the sign decided by `pauliAC` (16-case matrix computation); §2 the Kronecker SIGN theorem: `opsMat n f * opsMat n g = (−1)^|{i < n | AC(f i, g i)}| • (opsMat n g * opsMat n f)` (induction on `n`, one Kronecker factor at a time); §3 the sparse↔dense count bridge: for canonical `P` of width ≤ n the dense mismatch count over `range n` IS `acCount P Q`; §4 assembly: `commF` says the count is even, `(−1)^even = 1`. Width hypotheses are NECESSARY: a factor at qubit ≥ n is invisible to the `n`-qubit matrix, so the sparse and dense parities can disagree.
defpauliAC
def pauliAC : Pauli → Pauli → Bool
  | .X, .Y => true
  | .Y, .X => true
  | .X, .Z => true
  | .Z, .X => true
  | .Y, .Z => true
  | .Z, .Y => true
  | _,  _  => false
Do two single-qubit Paulis anticommute? (Exactly the six mixed pairs of distinct non-identity Paulis.)
theorempauli_mul_sign
theorem pauli_mul_sign (p q : Pauli) :
    p.toMatrix * q.toMatrix
      = (if pauliAC p q then (-1 : ℂ) else 1) • (q.toMatrix * p.toMatrix)
Single-qubit Paulis commute or anticommute, with the sign decided by `pauliAC` — by direct 2×2 matrix computation in all 16 cases.
theoremopsMat_succ
theorem opsMat_succ (n : Nat) (f : Nat → Pauli) :
    opsMat (n + 1) f
      = Matrix.reindex finProdFinEquiv finProdFinEquiv
          (Matrix.kroneckerMap (· * ·) (opsMat n (fun i => f (i + 1)))
            (f 0).toMatrix)
theoremreindexKron_mul
theorem reindexKron_mul {n : Nat}
    (A B : Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ)
    (a b : Matrix (Fin 2) (Fin 2) ℂ) :
    Matrix.reindex finProdFinEquiv finProdFinEquiv
        (Matrix.kroneckerMap (· * · : ℂ → ℂ → ℂ) A a)
      * Matrix.reindex finProdFinEquiv finProdFinEquiv
          (Matrix.kroneckerMap (· * ·) B b)
      = Matrix.reindex finProdFinEquiv finProdFinEquiv
          (Matrix.kroneckerMap (· * ·) (A * B) (a * b))
theoremcountP_map_succ
private theorem countP_map_succ (p : Nat → Bool) (l : List Nat) :
    (l.map Nat.succ).countP p = l.countP (fun i => p (i + 1))
theoremcountP_range_succ_shift
private theorem countP_range_succ_shift (p : Nat → Bool) (n : Nat) :
    (List.range (n + 1)).countP p
      = (List.range n).countP (fun i => p (i + 1)) + (if p 0 then 1 else 0)
theoremopsMat_mul_sign
theorem opsMat_mul_sign (n : Nat) (f g : Nat → Pauli) :
    opsMat n f * opsMat n g
      = ((-1 : ℂ) ^ ((List.range n).countP (fun i => pauliAC (f i) (g i)))) •
          (opsMat n g * opsMat n f)
*The Kronecker sign theorem**: two dense Pauli assignments commute up to the sign `(−1)^(number of anticommuting positions)`.
theoremwidth_le_factor_lt
theorem width_le_factor_lt {P : PauliProduct} {n : Nat}
    (h : PauliProduct.width P ≤ n) : ∀ f ∈ P, f.qubit < n
theoremkindFn_cons_self
theorem kindFn_cons_self (f : PFactor) (t : PauliProduct) :
    kindFn (f :: t) f.qubit = pkindToBQ f.kind
theoremkindFn_cons_ne
theorem kindFn_cons_ne (f : PFactor) (t : PauliProduct) (i : Nat)
    (h : f.qubit ≠ i) : kindFn (f :: t) i = kindFn t i
theoremkindFn_eq_I_of_lt_lbound
theorem kindFn_eq_I_of_lt_lbound {lo : Nat} {P : PauliProduct}
    (h : lbound lo P = true) {i : Nat} (hi : i < lo) : kindFn P i = .I
theorempauliAC_kind_lookup
theorem pauliAC_kind_lookup (k : PKind) (Q : PauliProduct) (i : Nat) :
    pauliAC (pkindToBQ k) (kindFn Q i) = overlapMismatch Q ⟨i, k⟩
`pauliAC` against a sparse lookup IS the syntactic `overlapMismatch`.
theoremcountP_congr'
private theorem countP_congr' {p q : Nat → Bool} :
    ∀ {l : List Nat}, (∀ a ∈ l, p a = q a) → l.countP p = l.countP q
theoremcountP_range_split
private theorem countP_range_split (n a : Nat) (ha : a < n) (p q : Nat → Bool)
    (heq : ∀ j, j ≠ a → q j = p j) (hpa : p a = false) :
    (List.range n).countP q = (List.range n).countP p + (if q a then 1 else 0)
theoremacCount_dense
theorem acCount_dense (n : Nat) (P Q : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n) :
    (List.range n).countP (fun i => pauliAC (kindFn P i) (kindFn Q i))
      = acCount P Q
*The count bridge**: for a canonical sparse product of width ≤ n, the dense anticommuting-position count over `range n` is exactly the syntactic `acCount`.
theoremaxisMat_comm_of_commF
theorem axisMat_comm_of_commF (n : Nat) {P Q : PauliProduct}
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n)
    (h : commF P Q = true) :
    axisMat n P * axisMat n Q = axisMat n Q * axisMat n P
*THE COMMUTATION BRIDGE**: syntactically commuting axes (`commF`) have commuting matrices. (`P` canonical and within width — the width bound is necessary, since out-of-range factors are invisible to the matrix.)
theoremRot.denote_swap
theorem Rot.denote_swap (n : Nat) (r s : Rot)
    (hs : sortedStrict s.axis = true) (hw : PauliProduct.width s.axis ≤ n)
    (h : commF s.axis r.axis = true) :
    Rot.denote n r * Rot.denote n s = Rot.denote n s * Rot.denote n r
*THE EXCHANGE LEMMA**: adjacent rotations whose axes commute syntactically swap without changing the denotation — the engine behind every reorder/parallelization transform. Only ONE side needs to be canonical and in-width.
example(example)
example :  -- X₀X₁ and Z₀Z₁ overlap everywhere yet commute — now at the MATRIX level
    axisMat 2 [⟨0, .x⟩, ⟨1, .x⟩] * axisMat 2 [⟨0, .z⟩, ⟨1, .z⟩]
      = axisMat 2 [⟨0, .z⟩, ⟨1, .z⟩] * axisMat 2 [⟨0, .x⟩, ⟨1, .x⟩]

FormalRV.PauliRotation.Semantics.Core

FormalRV/PauliRotation/Semantics/Core.lean
FormalRV.PauliRotation.Semantics.Core ──────────────────────────────── Matrix semantics for the Pauli-rotation IR — BY REUSE of the proven PPM matrix layer (`PPM/Semantics/LogicalState.lean`): • a rotation `e^{-iθP}` denotes `cos θ • 1 − (i sin θ) • P.toMatrix` (exact, since `P² = 1` — no matrix exponential needed); • the axis matrix comes from the EXISTING Kronecker interpretation `PauliString.toMatrix` through a sparse → dense bridge, inheriting the proven involution `toMatrix_mul_self`; • a layer denotes the product of its rotations; a program the composition of its layers (later layers act on the left). §2 proves the core rotation algebra over ANY involutive matrix: same-axis rotations MERGE angles (`rotOf_mul_same`), inverses CANCEL (`rotOf_cancel`), `π` rotations are the global phase `−1` (`rotOf_pi`) — these are the engines behind every optimization rule in `Rules.lean`.
defRAngle.val
noncomputable def RAngle.val : RAngle → ℝ
  | .pi        => Real.pi
  | .piHalf    => Real.pi / 2
  | .piQuarter => Real.pi / 4
  | .piEighth  => Real.pi / 8
The real angle of each discrete level.
defRot.theta
noncomputable def Rot.theta (r : Rot) : ℝ
The signed rotation angle of a rotation statement.
defrotOf
noncomputable def rotOf (θ : ℝ) (M : Matrix m m ℂ) : Matrix m m ℂ
`e^{-iθM}` for involutive `M`, in closed form.
theoremrotOf_pi_div_two
theorem rotOf_pi_div_two (M : Matrix m m ℂ) :
    rotOf (Real.pi / 2) M = (-Complex.I) • M
*π/2 rotations are the Pauli itself, up to the global phase −i.**
theoremrotOf_neg_pi_div_two
theorem rotOf_neg_pi_div_two (M : Matrix m m ℂ) :
    rotOf (-(Real.pi / 2)) M = Complex.I • M
theoremrotOf_mul_same
theorem rotOf_mul_same [Fintype m] {M : Matrix m m ℂ} (hM : M * M = 1) (θ φ : ℝ) :
    rotOf θ M * rotOf φ M = rotOf (θ + φ) M
*The merge law**: same-axis rotations compose by ADDING angles. This is the engine of rotation-merging optimization.
theoremrotOf_cancel
theorem rotOf_cancel [Fintype m] {M : Matrix m m ℂ} (hM : M * M = 1) (θ : ℝ) :
    rotOf θ M * rotOf (-θ) M = 1
*The cancellation law**: a rotation and its inverse compose to the identity.
theoremrotOf_comm
theorem rotOf_comm [Fintype m] {M N : Matrix m m ℂ} (h : M * N = N * M) (θ φ : ℝ) :
    rotOf θ M * rotOf φ N = rotOf φ N * rotOf θ M
*Commuting axes give commuting rotations** (any angles) — the engine behind parallel layers and rotation reordering.
defpkindToBQ
def pkindToBQ : PKind → Pauli
  | .x => .X
  | .y => .Y
  | .z => .Z
A sparse kind as a dense single-qubit Pauli (`BQCode` enum, the one with the proven matrix interpretation).
defkindFn
def kindFn (P : PauliProduct) (i : Nat) : Pauli
The dense Pauli a sparse axis applies at qubit `i` (`I` off-support).
deftoDenseOps
def toDenseOps (n : Nat) (P : PauliProduct) : PauliString
The dense ops list of a sparse axis at width `n`.
defopsMat
noncomputable def opsMat : (n : Nat) → (Nat → Pauli) → Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
  | 0,     _ => 1
  | n + 1, f =>
      Matrix.reindex finProdFinEquiv finProdFinEquiv
        (Matrix.kroneckerMap (· * ·) (opsMat n (fun i => f (i + 1))) (f 0).toMatrix)
The `2^n × 2^n` Kronecker interpretation of a dense qubit-indexed Pauli assignment — the same recursion shape as the proven `BQCode.PauliString.toMatrix` (qubit 0 is the innermost factor), but indexed by a FUNCTION `Nat → Pauli`, so that two axes can be inducted on simultaneously without dependent-length friction.
defaxisMat
noncomputable def axisMat (n : Nat) (P : PauliProduct) :
    Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
The axis as a `2^n × 2^n` matrix.
theoremopsMat_mul_self
theorem opsMat_mul_self (n : Nat) (f : Nat → Pauli) :
    opsMat n f * opsMat n f = 1
`opsMat` is an involution (each Kronecker factor squares to `1`, by the proven single-qubit `Pauli.toMatrix_mul_self`).
theoremaxisMat_mul_self
theorem axisMat_mul_self (n : Nat) (P : PauliProduct) :
    axisMat n P * axisMat n P = 1
The axis matrix is an involution.
defRot.denote
noncomputable def Rot.denote (n : Nat) (r : Rot) :
    Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
One rotation as a `2^n × 2^n` operator.
defRotLayer.denote
noncomputable def RotLayer.denote (n : Nat) (L : RotLayer) :
    Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
A layer as the product of its rotations (well-formed layers commute pairwise, so the listed order is one valid serialization).
defRotProg.denote
noncomputable def RotProg.denote (n : Nat) : RotProg → Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) ℂ
  | []     => 1
  | L :: p => RotProg.denote n p * RotLayer.denote n L
A program as the composition of its layers. CONVENTION: programs execute left-to-right, so later layers multiply on the LEFT (`⟦L :: p⟧ = ⟦p⟧ ⬝ ⟦L⟧`, matching `(U_k ⋯ U_1)ψ`).
theoremRotLayer.denote_cons
theorem RotLayer.denote_cons (n : Nat) (r : Rot) (L : RotLayer) :
    RotLayer.denote n (r :: L) = Rot.denote n r * RotLayer.denote n L
theoremRotProg.denote_append
theorem RotProg.denote_append (n : Nat) (p q : RotProg) :
    RotProg.denote n (p ++ q) = RotProg.denote n q * RotProg.denote n p
theoremRot.denote_mul_same_axis
theorem Rot.denote_mul_same_axis (n : Nat) (r s : Rot) (h : r.axis = s.axis) :
    Rot.denote n r * Rot.denote n s
      = rotOf (r.theta + s.theta) (axisMat n r.axis)
*Same-axis merge at the denotation level**: two rotations about the same axis compose into the angle-sum rotation.
defRot.inv
def Rot.inv (r : Rot) : Rot
The angle-flipped inverse of a rotation.
theoremRot.inv_theta
theorem Rot.inv_theta (r : Rot) : r.inv.theta = -r.theta
theoremRot.denote_mul_inv
theorem Rot.denote_mul_inv (n : Nat) (r : Rot) :
    Rot.denote n r * Rot.denote n r.inv = 1
*Cancellation at the denotation level**: `r · r⁻¹ = 1`.
theoremRot.denote_pi
theorem Rot.denote_pi (n : Nat) (r : Rot) (h : r.angle = .pi) :
    Rot.denote n r = -1
*π rotations are global phases at the denotation level** — whatever the axis, a `±π` rotation denotes `−1`.

FormalRV.PauliRotation.Semantics.PauliPhase

FormalRV/PauliRotation/Semantics/PauliPhase.lean
FormalRV.PauliRotation.Semantics.PauliPhase ───────────────────────────────── *THE PHASE-TRACKED PAULI PRODUCT — the optimization keystone.** The frame product `mulF` (PPM/Syntax/PauliAlgebra) multiplies sparse Pauli products MOD PHASE. This file supplies the missing phase and welds the pair to the matrix semantics: axisMat n P * axisMat n Q = i^(phaseF P Q) • axisMat n (mulF P Q) for canonical `P` within width and canonical `Q`. This single theorem is what turns Litinski-style Clifford pushing (`rot_quarter_push`, which conjugates axes as MATRICES) into verified SYNTACTIC rewrites on the rotation IR — the new axis is `mulF P Q` and the sign lands in the `neg` flag (anticommuting products always carry phase ±i). Build mirrors the proven CommBridge architecture exactly: §1 dense single-qubit product with phase (`bqMul`/`bqPhase`, `pauli_mul_full` — 16-case 2×2 computation); §2 the Kronecker lift (`opsMat_mul_full` — induction via `reindexKron_mul`, phases add); §3 sparse ↔ dense bridges (`phaseF_dense` mirrors `acCount_dense`; `kindFn_mulF` is the pointwise kind law over the sorted merge); §4 THE KEYSTONE `axisMat_mulF` + parity corollaries reconciling `phaseF` with `commF`/`acCount`.
defbqMul
def bqMul : Pauli → Pauli → Pauli
  | .I, q => q
  | p, .I => p
  | .X, .X => .I
  | .Y, .Y => .I
  | .Z, .Z => .I
  | .X, .Y => .Z
  | .Y, .X => .Z
  | .Y, .Z => .X
  | .Z, .Y => .X
  | .Z, .X => .Y
  | .X, .Z => .Y
Single-qubit Pauli product, kind component (`I` absorbs; equal kinds cancel; distinct kinds give the third).
defbqPhase
def bqPhase : Pauli → Pauli → ℕ
  | .X, .Y => 1
  | .Y, .Z => 1
  | .Z, .X => 1
  | .Y, .X => 3
  | .Z, .Y => 3
  | .X, .Z => 3
  | _, _ => 0
Single-qubit Pauli product, phase exponent: `p·q = i^(bqPhase p q)·(bqMul p q)`. Cyclic order `X→Y→Z` gives `+i` (exponent 1), reversed gives `−i` (exponent 3).
theorempauli_mul_full
theorem pauli_mul_full (p q : Pauli) :
    p.toMatrix * q.toMatrix
      = (Complex.I ^ bqPhase p q) • (bqMul p q).toMatrix
*The 2×2 phase-tracked product**: every pair of single-qubit Paulis multiplies to `i^(bqPhase)` times the `bqMul` kind — all 16 cases by direct matrix computation.
theoremmap_sum_range_succ
private theorem map_sum_range_succ (h : Nat → ℕ) (n : Nat) :
    ((List.range (n + 1)).map h).sum
      = ((List.range n).map (fun i => h (i + 1))).sum + h 0
theoremopsMat_mul_full
theorem opsMat_mul_full (n : Nat) (f g : Nat → Pauli) :
    opsMat n f * opsMat n g
      = (Complex.I ^ (((List.range n).map (fun i => bqPhase (f i) (g i))).sum))
          • opsMat n (fun i => bqMul (f i) (g i))
*The Kronecker product theorem**: dense Pauli assignments multiply pointwise, with the phase exponents SUMMING across qubits.
defphaseAt
def phaseAt (Q : PauliProduct) (f : PFactor) : ℕ
The per-factor phase of `f` against the product `Q` (0 off `Q`'s support).
defphaseF
def phaseF (P Q : PauliProduct) : ℕ
*The product phase exponent**: the sum of per-factor phases of `P` against `Q` — `i^(phaseF P Q)` is the phase of `P·Q` relative to `mulF P Q`.
theoremphaseF_cons
theorem phaseF_cons (f : PFactor) (P Q : PauliProduct) :
    phaseF (f :: P) Q = phaseAt Q f + phaseF P Q
theorembqPhase_kind_lookup
theorem bqPhase_kind_lookup (k : PKind) (Q : PauliProduct) (i : Nat) :
    bqPhase (pkindToBQ k) (kindFn Q i) = phaseAt Q ⟨i, k⟩
`bqPhase` against a sparse lookup IS the syntactic `phaseAt`.
theoremsum_range_split
private theorem sum_range_split (n a : Nat) (ha : a < n) (p q : Nat → ℕ)
    (heq : ∀ j, j ≠ a → q j = p j) (hpa : p a = 0) :
    ((List.range n).map q).sum = ((List.range n).map p).sum + q a
theoremphaseF_dense
theorem phaseF_dense (n : Nat) (P Q : PauliProduct)
    (hs : sortedStrict P = true) (hw : PauliProduct.width P ≤ n) :
    ((List.range n).map (fun i => bqPhase (kindFn P i) (kindFn Q i))).sum
      = phaseF P Q
*The phase bridge**: for canonical `P` within width, the dense phase sum over `range n` IS the syntactic `phaseF`.
theorembqMul_of_mulK_none
theorem bqMul_of_mulK_none {a b : PKind} (h : PKind.mulK a b = none) :
    bqMul (pkindToBQ a) (pkindToBQ b) = .I
theorembqMul_of_mulK_some
theorem bqMul_of_mulK_some {a b k : PKind} (h : PKind.mulK a b = some k) :
    bqMul (pkindToBQ a) (pkindToBQ b) = pkindToBQ k
theoremkindFn_eq_I_of_not_lt
theorem kindFn_eq_I_of_not_lt {P : PauliProduct} {lo i : Nat}
    (hlb : lbound lo P = true) (hi : i < lo) : kindFn P i = .I
theoremkindFn_mulF
theorem kindFn_mulF (P Q : PauliProduct)
    (hsP : sortedStrict P = true) (hsQ : sortedStrict Q = true) (i : Nat) :
    kindFn (mulF P Q) i = bqMul (kindFn P i) (kindFn Q i)
*The pointwise kind law**: the sorted-merge product looks up, qubit by qubit, as the dense single-qubit product of the factors' lookups.
theoremaxisMat_mulF
theorem axisMat_mulF (n : Nat) (P Q : PauliProduct)
    (hsP : sortedStrict P = true) (hwP : PauliProduct.width P ≤ n)
    (hsQ : sortedStrict Q = true) :
    axisMat n P * axisMat n Q
      = (Complex.I ^ phaseF P Q) • axisMat n (mulF P Q)
*THE PHASE-TRACKED PRODUCT THEOREM**: the matrix product of two canonical axes is `i^(phaseF P Q)` times the axis of the frame product `mulF P Q`. This welds the phase-free frame algebra to the matrix semantics and is the engine of verified Clifford pushing.
theoremphaseAt_parity
theorem phaseAt_parity (Q : PauliProduct) (f : PFactor) :
    phaseAt Q f % 2 = (if overlapMismatch Q f then 1 else 0)
theoremphaseF_parity
theorem phaseF_parity (P Q : PauliProduct) :
    phaseF P Q % 2 = acCount P Q % 2
The phase parity IS the anticommutation parity.
theoremphaseF_even_of_commF
theorem phaseF_even_of_commF {P Q : PauliProduct}
    (h : commF P Q = true) : phaseF P Q % 2 = 0
Commuting axes have an EVEN phase (`i^phaseF = ±1`).
theoremphaseF_odd_of_not_commF
theorem phaseF_odd_of_not_commF {P Q : PauliProduct}
    (h : commF P Q = false) : phaseF P Q % 2 = 1
Anticommuting axes have an ODD phase (`i^phaseF = ±i`) — the sign that Clifford pushing folds into the `neg` flag.
theoremI_pow_mod
theorem I_pow_mod (k : Nat) : Complex.I ^ k = Complex.I ^ (k % 4)
`i^k` only depends on `k % 4`.

FormalRV.PauliRotation.Syntax

FormalRV/PauliRotation/Syntax.lean
FormalRV.PauliRotation.Syntax ───────────────────────────── THE PAULI-ROTATION IR (John's directive, 2026-06-10) — the standard Litinski layer between the logical circuit IRs and the PPM program IR: circuit ──compile──▶ Pauli rotations e^{-iθP}, θ ∈ ±{π, π/2, π/4, π/8} ──reorganize / group commuting rotations into PARALLEL layers── ──lower──▶ PPM programs (`PPM/Syntax/Program.lean`) A program here is a list of LAYERS; a layer is a list of rotations whose axes pairwise commute, so they are executable in parallel — the program length IS the parallel logical depth. The angle dictionary (full-angle Litinski convention `P_θ = e^{-iθP}`): θ = π : global phase −1 (droppable) θ = π/2 : the Pauli `P` itself, up to phase −i (frame level) θ = π/4 : Clifford level (S = Z_{π/4}; H, CNOT = products of ±π/4) θ = π/8 : T level (T = Z_{π/8}) — the only non-Clifford, hence `countPi8` IS the T-count Signs are necessary: `T†`/`S†` rotations appear in the standard CCZ seven-rotation phase polynomial and in the CNOT/H decompositions, so each rotation carries `neg`. NO ancilla / syndrome qubits exist at this layer — rotations act on logical data qubits only (ancillas appear only when lowering π/8 rotations to PPM measurements). This file is the LEAF of the layer: it imports ONLY the sparse Pauli product syntax (`PPM/Syntax/Program.lean`, itself zero-import), so the `Resource/` counters may walk this tree (honest-resource discipline). Semantics: `Semantics.lean`; optimization rules: `Rules.lean`.
inductiveRAngle
inductive RAngle
A discrete rotation angle `θ ∈ {π, π/2, π/4, π/8}` (full-angle Litinski convention `e^{-iθP}`): `pi` = global phase, `piHalf` = Pauli level, `piQuarter` = Clifford level, `piEighth` = T level (non-Clifford).
defRAngle.eighths
def RAngle.eighths : RAngle → Nat
  | .pi => 8 | .piHalf => 4 | .piQuarter => 2 | .piEighth => 1
The angle in units of π/8 (for merge arithmetic: `pi` = 8, …, `piEighth` = 1).
structureRot
structure Rot
One Pauli-product rotation `e^{∓iθ·axis}` (`neg = true` is the `+i` direction, i.e. angle `−θ`: `T† = Z_{−π/8}`). The axis is a sparse canonical Pauli product on the LOGICAL data qubits — no ancillas at this layer.
abbrevRotLayer
abbrev RotLayer
A PARALLEL layer: rotations whose axes pairwise commute (enforced by `RotLayer.wf`), hence simultaneously executable. One layer = one unit of parallel logical depth.
abbrevRotProg
abbrev RotProg
A Pauli-rotation program: a sequence of parallel layers.
defoverlapMismatch
def overlapMismatch (Q : PauliProduct) (f : PFactor) : Bool
Does `f`'s qubit appear in `Q` with a different (anticommuting) kind?
defacCount
def acCount (P Q : PauliProduct) : Nat
The number of anticommuting overlap positions between two products.
defcommF
def commF (P Q : PauliProduct) : Bool
*Commutation test**: `P` and `Q` commute iff the anticommuting overlap count is even.
defRot.wf
def Rot.wf (r : Rot) : Bool
A rotation is well-formed when its axis is canonical and nonempty. (`pi` rotations are also well-formed — they are global phases, removable by the optimizer, but the compiler is allowed to emit them.)
deflayerComm
def layerComm : RotLayer → Bool
  | []     => true
  | r :: t => t.all (fun s => commF r.axis s.axis) && layerComm t
All ordered pairs in the layer commute (suffices: commutation of the underlying products is symmetric).
defRotLayer.wf
def RotLayer.wf (L : RotLayer) : Bool
*Layer well-formedness**: every rotation well-formed, all axes pairwise commuting — the layer is executable in parallel.
defRotProg.wf
def RotProg.wf (p : RotProg) : Bool
*Program well-formedness**: every layer well-formed.
defRot.width
def Rot.width (r : Rot) : Nat
Quantum width of a rotation: the qubits its axis touches.
defRotLayer.width
def RotLayer.width : RotLayer → Nat
  | []     => 0
  | r :: t => max r.width (RotLayer.width t)
Quantum width of a layer.
defRotProg.width
def RotProg.width : RotProg → Nat
  | []     => 0
  | L :: p => max L.width (RotProg.width p)
*Quantum width** of a program: the number of logical qubits it touches. There are no ancillas at this layer, so this is the DATA width.
theoremlayerComm_append
theorem layerComm_append (L M : RotLayer) :
    layerComm (L ++ M) = true ↔
      (layerComm L = true ∧ layerComm M = true ∧
        ∀ r ∈ L, ∀ s ∈ M, commF r.axis s.axis = true)
Appending parallel layers: the result is pairwise-commuting iff both parts are and every cross pair commutes.
theoremRotProg.wf_append
theorem RotProg.wf_append (p q : RotProg) :
    RotProg.wf (p ++ q) = (RotProg.wf p && RotProg.wf q)
theoremRotProg.width_append
theorem RotProg.width_append (p q : RotProg) :
    RotProg.width (p ++ q) = max (RotProg.width p) (RotProg.width q)
example(example)
example : commF [⟨0, .x⟩, ⟨1, .x⟩] [⟨1, .z⟩, ⟨2, .z⟩] = false
example(example)
example : commF [⟨0, .x⟩, ⟨1, .x⟩] [⟨0, .z⟩, ⟨1, .z⟩] = true
example(example)
example : commF [⟨0, .x⟩] [⟨5, .z⟩] = true
example(example)
example : commF [⟨0, .x⟩, ⟨3, .z⟩] [⟨0, .x⟩, ⟨3, .z⟩] = true
example(example)
example : RotLayer.wf
    [⟨false, .piEighth, [⟨0, .z⟩]⟩, ⟨false, .piEighth, [⟨1, .z⟩]⟩] = true
example(example)
example : RotLayer.wf
    [⟨false, .piQuarter, [⟨0, .x⟩, ⟨1, .x⟩]⟩,
     ⟨true,  .piQuarter, [⟨0, .z⟩, ⟨1, .z⟩]⟩] = true
example(example)
example : RotLayer.wf
    [⟨false, .piEighth, [⟨0, .x⟩]⟩, ⟨false, .piEighth, [⟨0, .z⟩]⟩] = false
example(example)
example : RotProg.width
    [[⟨false, .piEighth, [⟨0, .z⟩, ⟨4, .x⟩]⟩], [⟨true, .pi, [⟨2, .y⟩]⟩]] = 5