Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

Effective guard enumeration and padded input

Definition
rsg_quartic_runtime_06

by sirawit · Nov 30, 2026 · Mathlib 0df444a (Lean v4.33.1)

complexity-theorygraph-theorygroup-theory

Defines ordered guard sections, the padded SAT input and its time envelope, and the field and coordinate operations used in the effective typed model.

Definition code
import Definitions.Def_rsg_quartic_runtime_05
import Mathlib
import Definitions.Def_rsg_paper_structure
import Mathlib.LinearAlgebra.Pi
import Mathlib.Data.Fintype.EquivFin
import Mathlib.Data.Finset.Card
import Mathlib.Tactic.Abel
import Definitions.Def_rsg_recognition_core
import Mathlib.Data.Fintype.BigOperators
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
import Mathlib.GroupTheory.PGroup
import Mathlib.GroupTheory.Nilpotent
import Mathlib.Combinatorics.SimpleGraph.Coloring.Vertex
import Mathlib.LinearAlgebra.Basis.VectorSpace
import Mathlib.LinearAlgebra.Isomorphisms
import Mathlib.Logic.Equiv.Defs
import Mathlib.Data.Fintype.Basic
import Mathlib.Data.Finset.Erase
import Mathlib.Logic.Function.Basic
import Mathlib.Data.Fintype.Sigma
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
import Mathlib.LinearAlgebra.Dual.Defs
import Mathlib.LinearAlgebra.Basis.Prod
import Mathlib.LinearAlgebra.Dual.Basis
import Mathlib.Algebra.CharP.Two
import Mathlib.Algebra.Polynomial.Roots
import Mathlib.Data.Set.Card
import Mathlib.FieldTheory.Finite.Trace
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Ring
import Mathlib.LinearAlgebra.BilinearForm.Orthogonal
import Mathlib.LinearAlgebra.Dimension.Finrank
import Mathlib.FieldTheory.Finite.GaloisField
import Mathlib.Logic.Equiv.Fin.Basic
import Definitions.Def_rsg_paper_complexity
import Mathlib.Data.Finite.Sum
import Mathlib.Data.Fintype.Sum
import Mathlib.Data.ZMod.Basic
import Mathlib.Tactic.FinCases
import Mathlib.Data.Fin.VecNotation
import Mathlib.Data.Fintype.Prod
import Definitions.Def_rsg_paper_vig_strip
import Mathlib.Logic.Equiv.Sum
import Definitions.Def_QuantumMaxCutFiniteNumericRuntime
import Mathlib.Combinatorics.SimpleGraph.Bipartite
import Mathlib.Data.List.NodupEquivFin
import Mathlib.Analysis.SpecialFunctions.Log.Base
import Mathlib.Algebra.Field.ZMod
import Mathlib.LinearAlgebra.Dual.Lemmas
import Definitions.Def_QuantumMaxCutEnergyEstimationModel

section

set_option autoImplicit false

namespace RSGPaper.QuarticEffectiveSteps

open QuarticGraphSteps
open QuarticGraphColors
open QuarticPalette
open QuarticGuardTable
open QuarticCanonicalProfiles
open QuarticVertexNumbers
open ChartNumericInput
open QuarticEffectiveChart

def cubes (n : ℕ) : List (Pos n) := List.ofFn (cubeIndex n).symm

theorem mem_cubes (n : ℕ) (x : Pos n) : x ∈ cubes n :=
  List.mem_ofFn.mpr ⟨cubeIndex n x,(cubeIndex n).symm_apply_apply x⟩

def factors : List Factor :=
  ((List.finRange 7).flatMap fun j => [primary j false,primary j true]) ++ [.inr false,.inr true]

theorem mem_factors (k : Factor) : k ∈ factors := by
  rcases k with ⟨j,b⟩ | b
  · apply List.mem_append_left
    apply List.mem_flatMap.mpr
    refine ⟨j,List.mem_finRange j,?_⟩
    cases b <;> simp [primary]
  · apply List.mem_append_right
    cases b <;> simp

def positions (d : ℕ) : List (Positions (fun _ => d)) := (cubes (14*d+2)).map (flatten d).symm

variable {side : ℕ}

abbrev StepAt (side : ℕ) := Step (fun _ => posWidth side)

abbrev ClauseDirections (side : ℕ) := Clause side → Channel → Pos (posWidth side)

def candidates (directions : ClauseDirections side) (clauses : List (Clause side)) : List (StepAt side) :=
  ((List.finRange 7).flatMap (fun j => (cubes (posWidth side)).flatMap fun a =>
    [.primary j false a,.primary j true a,.comparison j a,.guard j false a,.guard j true a]) ++
  [.binary false,.binary true]) ++ clauses.map (fun c => .clause (directions c))

theorem valid_in_candidates (directions : ClauseDirections side) (exactDirs : directions = clauseDirections)
    (clauses : List (Clause side)) (s : StepAt side) (ok : Valid (QuarticGuardTable.rules clauses) s) :
    s ∈ candidates directions clauses := by
  subst directions
  have at_one (j : Channel) (a : Pos (posWidth side)) (s : StepAt side)
      (listed : s ∈ ([.primary j false a,.primary j true a,.comparison j a,.guard j false a,.guard j true a] : List (StepAt side))) :
      s ∈ candidates clauseDirections clauses := by
    apply List.mem_append_left
    apply List.mem_append_left
    exact List.mem_flatMap.mpr ⟨j,List.mem_finRange j,List.mem_flatMap.mpr ⟨a,mem_cubes _ _,listed⟩⟩
  cases s with
  | primary j b a => cases b <;> exact at_one j a _ (by simp)
  | binary b => apply List.mem_append_left; apply List.mem_append_right; cases b <;> simp
  | clause a =>
    obtain ⟨c,present,rfl⟩ := ok
    exact List.mem_append_right _ (List.mem_map_of_mem (f := fun q => Step.clause (clauseDirections q)) present)
  | comparison j a => exact at_one j a _ (by simp)
  | guard j b a => cases b <;> exact at_one j a _ (by simp)

def geometryBit (side : ℕ) (a : Pos (posWidth side)) : Bool :=
  let x := (QuarticChannelLayout.layout side).position a
  decide (x.2.2 = 1) && decide (CubicGauge.dot x.1 x.2.1 = 1)

def equalPositions (d : ℕ) (a b : Positions (fun _ => d)) : Bool :=
  decide (vectorCode (flatten d a) = vectorCode (flatten d b))

theorem equalPositions_correct (d : ℕ) (a b : Positions (fun _ => d)) : equalPositions d a b = true ↔ a = b := by
  unfold equalPositions
  rw [decide_eq_true_eq]
  exact ((vectorCode_injective _).comp (flatten d).injective).eq_iff

def equalClause (d : ℕ) (a b : Channel → Pos d) : Bool :=
  (List.finRange 7).all (fun j => decide (vectorCode (a j) = vectorCode (b j)))

theorem equalClause_correct (d : ℕ) (a b : Channel → Pos d) : equalClause d a b = true ↔ a = b := by
  constructor
  · intro equal
    funext j
    have code := List.all_eq_true.mp equal j (List.mem_finRange j)
    exact vectorCode_injective d (of_decide_eq_true code)
  · rintro rfl
    simp [equalClause]

theorem zero_code {n : ℕ} (x : Pos n) : vectorCode x = 0 ↔ x = 0 := by
  rw [← vectorCode_zero n]
  exact (vectorCode_injective n).eq_iff

def validBit (directions : ClauseDirections side) (clauses : List (Clause side)) : StepAt side → Bool
  | .primary _ _ a => geometryBit side a
  | .binary _ => true
  | .clause a => clauses.any (fun c => equalClause (posWidth side) a (directions c))
  | .comparison _ a | .guard _ _ a => decide (vectorCode a ≠ 0)

theorem validBit_correct (directions : ClauseDirections side) (exactDirs : directions = clauseDirections)
    (clauses : List (Clause side)) (s : StepAt side) :
    validBit directions clauses s = true ↔ Valid (QuarticGuardTable.rules clauses) s := by
  subst directions
  cases s with
  | primary j b a =>
    change (geometryBit side a = true) ↔ _
    simp [geometryBit,QuarticGuardTable.rules,Valid,QuarticPrimaryLayout.rules,
      QuarticPrimaryLayout.geometrySteps,QuarticDirectionSpan.geometry]
  | binary b => simp [validBit,Valid]
  | clause a =>
    change clauses.any (fun c => equalClause (posWidth side) a (clauseDirections c)) = true ↔
      ∃ c ∈ clauses, a = clauseDirections c
    simp [List.any_eq_true,equalClause_correct]
  | comparison j a =>
    change decide (vectorCode a ≠ 0) = true ↔ a ≠ 0
    rw [decide_eq_true_eq]
    exact not_congr (zero_code a)
  | guard j b a =>
    change decide (vectorCode a ≠ 0) = true ↔ a ≠ 0
    rw [decide_eq_true_eq]
    exact not_congr (zero_code a)

def validSteps (directions : ClauseDirections side) (clauses : List (Clause side)) : List (StepAt side) :=
  (candidates directions clauses).filter (validBit directions clauses)

theorem mem_validSteps (directions : ClauseDirections side) (exactDirs : directions = clauseDirections)
    (clauses : List (Clause side)) (s : StepAt side) :
    s ∈ validSteps directions clauses ↔ Valid (QuarticGuardTable.rules clauses) s := by
  rw [validSteps,List.mem_filter,validBit_correct directions exactDirs]
  exact ⟨And.right,fun ok => ⟨valid_in_candidates directions exactDirs clauses s ok,ok⟩⟩

variable {d r : ℕ}

def supportsBit (p : Positions (fun _ => d)) (z : Labels (fun _ => r)) : Bool :=
  factors.all (fun i => !decide (vectorCode (p i) = 0) || decide (vectorCode (z i) = 0))

theorem supportsBit_correct (p : Positions (fun _ => d)) (z : Labels (fun _ => r)) :
    supportsBit p z = true ↔ ∀ i, p i = 0 → z i = 0 := by
  simp only [supportsBit,List.all_eq_true,Bool.or_eq_true,Bool.not_eq_true',decide_eq_false_iff_not,decide_eq_true_eq]
  constructor
  · intro h i pi
    have ok := h i (mem_factors i)
    exact (zero_code (z i)).mp (ok.resolve_left (fun neq => neq ((zero_code (p i)).mpr pi)))
  · intro h i _
    by_cases pi : p i = 0
    · exact Or.inr ((zero_code (z i)).mpr (h i pi))
    · exact Or.inl (fun eq => pi ((zero_code (p i)).mp eq))

def accepts (R : Rules (fun _ => d) (fun _ => r)) (valid : Step (fun _ => d) → Bool)
    (w : Vertex (fun _ => d) (fun _ => r)) (s : Step (fun _ => d)) : Bool :=
  (valid s && equalPositions d (position R s) w.1) && supportsBit (position R s) w.2

theorem accepts_correct (R : Rules (fun _ => d) (fun _ => r)) (valid : Step (fun _ => d) → Bool)
    (exactValid : ∀ s, valid s = true ↔ Valid R s)
    (w : Vertex (fun _ => d) (fun _ => r)) (s : Step (fun _ => d)) :
    accepts R valid w s = true ↔ Matches R w s := by
  simp only [accepts,Bool.and_eq_true,equalPositions_correct,supportsBit_correct,exactValid,Matches,Supported,and_assoc]

end RSGPaper.QuarticEffectiveSteps

end

section

set_option autoImplicit false

namespace RSGPaper.QuarticEffectiveLinearForms

open QuarticGraphSteps
open QuarticEffectiveSteps
open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticCanonicalProfiles

variable {A : Type} [AddCommGroup A] [Module Bit A] {n : ℕ}

def fromCoefficients (coord : A ≃ₗ[Bit] Pos n) (coeff : Pos n) : A →ₗ[Bit] Bit :=
  (CubicGauge.dotLinear coeff).comp coord.toLinearMap

def enumerate (coord : A ≃ₗ[Bit] Pos n) : List (A →ₗ[Bit] Bit) :=
  (cubes n).map (fromCoefficients coord)

def nativePositions (side : ℕ) : List (Position side) := (cubes (posWidth side)).map (layout side).position

theorem mem_nativePositions (side : ℕ) (x : Position side) : x ∈ nativePositions side :=
  List.mem_map.mpr ⟨(layout side).position.symm x,mem_cubes _ _,LinearEquiv.apply_symm_apply _ _⟩

def positionForms (side : ℕ) : List (Position side →ₗ[Bit] Bit) := enumerate (layout side).position.symm

def dataForms (side : ℕ) : List (Data side →ₗ[Bit] Bit) :=
  enumerate (LinearEquiv.refl Bit (Data side))

end RSGPaper.QuarticEffectiveLinearForms

end

section

set_option autoImplicit false
set_option maxHeartbeats 1400000

namespace RSGPaper.QuarticEffectiveGuardTests

open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticNativeSecond
open QuarticFieldCoordinates
open QuarticGuardTable
open QuarticAuxJoint
open QuarticCoreHyperplane
open QuarticDataTensor
open QuarticCoreProjection
open QuarticGraphSteps
open QuarticEffectiveSteps

variable {side : ℕ}

theorem auxiliary_ann_iff (u : Data side) (ℓ : Data side →ₗ[Bit] Bit) :
    Ann u ℓ ↔ ∀ x y, ℓ (auxPart side (tensor (model side) u x y)) = 0 := by
  constructor
  · intro h x y
    exact h _ ⟨_,Submodule.subset_span ⟨x,y,rfl⟩,rfl⟩
  · intro h z member
    obtain ⟨p,inside,rfl⟩ := member
    have reads : contracted (model side) u ≤ (ℓ.comp (auxPart side)).ker := by
      apply Submodule.span_le.mpr
      rintro _ ⟨x,y,rfl⟩
      exact h x y
    exact reads inside

 abbrev width (side : ℕ) := fieldWidth (dataWidth side)

def lower (side : ℕ) (u v : Pos (width side)) : Position side :=
  ((blocks (dataWidth side)).symm (u,v,0),0,0)

theorem lowerImage (side : ℕ) (u v : Pos (width side)) :
    ∃ g : QuarticSecondPolar.Gradient (E (dataWidth side)),
      g.2.2 = 0 ∧ embedding (dataWidth side) g = lower side u v := by
  let raw := (blocks (dataWidth side)).symm (u,v,0)
  refine ⟨outputFields (dataWidth side) raw,?_,?_⟩
  · unfold outputFields
    rw [LinearEquiv.trans_apply]
    change (coordinates (width side) _ ((blocks (dataWidth side) raw).2.2)) = 0
    unfold raw
    rw [LinearEquiv.apply_symm_apply,map_zero]
  · change ((outputFields (dataWidth side)).symm (outputFields (dataWidth side) raw),0,0) = _
    rw [LinearEquiv.symm_apply_apply]
    rfl

theorem imageLower (side : ℕ) (g : QuarticSecondPolar.Gradient (E (dataWidth side))) (zero : g.2.2 = 0) :
    ∃ u v, embedding (dataWidth side) g = lower side u v := by
  let raw := (outputFields (dataWidth side)).symm g
  let values := blocks (dataWidth side) raw
  have value : outputFields (dataWidth side) raw = g := LinearEquiv.apply_symm_apply _ _
  have last : values.2.2 = 0 := by
    let C := coordinates (width side) (show width side ≠ 0 by unfold width fieldWidth; omega)
    apply C.injective
    have read := (congrArg (fun z => z.2.2) value).trans zero
    change C values.2.2 = 0 at read
    rwa [map_zero]
  refine ⟨values.1,values.2.1,?_⟩
  change (raw,0,0) = ((blocks (dataWidth side)).symm (values.1,values.2.1,0),0,0)
  have packed : (values.1,values.2.1,0) = values := Prod.ext rfl (Prod.ext rfl last.symm)
  rw [packed]
  change (raw,0,0) = ((blocks (dataWidth side)).symm (blocks (dataWidth side) raw),0,0)
  rw [LinearEquiv.symm_apply_apply]

theorem second_support_iff (ℓ : Position side →ₗ[Bit] Bit) :
    secondSupport ℓ ↔ ∀ x y, ℓ (lower side x y) = 0 := by
  constructor
  · intro support x y
    obtain ⟨g,zero,image⟩ := lowerImage side x y
    exact image ▸ support g zero
  · intro all g zero
    obtain ⟨x,y,eq⟩ := imageLower side g zero
    rw [eq]
    exact all x y

def testsSecond (ℓ : Position side →ₗ[Bit] Bit) : Bool :=
  (cubes (width side)).all (fun x => (cubes (width side)).all (fun y => decide (ℓ (lower side x y) = 0)))

theorem testsSecond_correct (ℓ : Position side →ₗ[Bit] Bit) : testsSecond ℓ = true ↔ secondSupport ℓ := by
  rw [second_support_iff]
  simp only [testsSecond,List.all_eq_true,decide_eq_true_eq]
  exact ⟨fun h x y => h x (mem_cubes _ _) y (mem_cubes _ _),fun h x _ y _ => h x y⟩

def testsAux (t : Data side → Data side → Data side → Data side) (u : Data side)
    (ℓ : Data side →ₗ[Bit] Bit) : Bool :=
  (cubes (dataWidth side)).all (fun x => (cubes (dataWidth side)).all
    (fun y => decide (ℓ (auxPart side (t u x y)) = 0)))

theorem testsAux_correct (t : Data side → Data side → Data side → Data side) (eq : t = tensor (model side))
    (u : Data side) (ℓ : Data side →ₗ[Bit] Bit) : testsAux t u ℓ = true ↔ Ann u ℓ := by
  rw [eq,auxiliary_ann_iff]
  simp only [testsAux,List.all_eq_true,decide_eq_true_eq]
  exact ⟨fun h x y => h x (mem_cubes _ _) y (mem_cubes _ _),fun h x _ y _ => h x y⟩

end RSGPaper.QuarticEffectiveGuardTests

end

section

set_option autoImplicit false

namespace RSGPaper.QuarticGuardEntries

open QuarticGraphSteps
open QuarticCanonicalProfiles
open QuarticGuardTable
open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticEffectiveSteps
open QuarticEffectiveLinearForms
open ChartNumericInput

variable {side : ℕ}

abbrev Entry (clauses : List (Clause side)) (channel : Channel) (copy : Bool) :=
  Σ x : Position side, {r : NativeRow side // Request clauses channel copy x r}

def entry {clauses : List (Clause side)} {channel : Channel} {copy : Bool}
    {x : Position side} {row : NativeRow side} (holds : Request clauses channel copy x row) :
    Entry clauses channel copy := ⟨x,⟨row,holds⟩⟩

def selected {X Y : Type} {P : X → Prop} (items : List X) (test : X → Bool)
    (correct : ∀ x, test x = true ↔ P x) (emit : (x : X) → P x → Y) : List Y :=
  items.filterMap fun x => if h : test x = true then some (emit x ((correct x).mp h)) else none

def equalNative (x y : Position side) : Bool :=
  decide (vectorCode ((layout side).position.symm x) = vectorCode ((layout side).position.symm y))

def rowsAt {clauses : List (Clause side)} {channel : Channel} {copy : Bool}
    (source : List (Entry clauses channel copy)) (x : Position side) : List ((Lab (labWidth side) →ₗ[Bit] Bit) × Bit) :=
  (source.filter fun item => equalNative x item.1).map fun item => package item.2.val

def dataIndices (side : ℕ) : List (DataIndex side) :=
  (List.finRange (dataWidth side)).map (QuarticSliceCoefficients.index side).symm

def notRealBit (i : DataIndex side) : Bool :=
  match i with
  | .inl (_,j) => decide (side ≤ j.val)
  | .inr _ => true

theorem notRealBit_correct (i : DataIndex side) : notRealBit i = true ↔ ¬QuarticFreeEntries.IsReal i := by
  rcases i with ⟨g,j⟩ | aux <;> simp [notRealBit,QuarticFreeEntries.IsReal]

def pairs {X Y : Type} (as : List X) (bs : List Y) : List (X × Y) :=
  as.flatMap fun a => bs.map fun b => (a,b)

end RSGPaper.QuarticGuardEntries

end

section

set_option autoImplicit false
set_option maxHeartbeats 1700000

namespace RSGPaper.QuarticGuardDataEntries

open QuarticGraphSteps
open QuarticLiteralDirection
open QuarticCanonicalProfiles
open QuarticProjectedData
open QuarticGuardTable
open QuarticChannelLayout
open QuarticGuardEntries
open QuarticEffectiveSteps
open QuarticEffectiveLinearForms
open ChartNumericInput
open BooleanMonomials
open CubicGauge

variable {side : ℕ}
variable (clauses : List (Clause side)) (j : Channel) (copy : Bool)

def outside : List (Entry clauses j copy) :=
  (selected (nativePositions side) (fun x => decide (vectorCode (read side x) = 0))
    (fun x => by rw [decide_eq_true_eq,zero_code])
    (fun x h => (⟨x,h⟩ : {p : Position side // read side p = 0}))).flatMap fun h =>
      (List.finRange (dataWidth side)).map fun i => entry (Request.outsideData h.1 h.2 i)

 def indexPairs (side : ℕ) : List (Fin (dataWidth side) × Fin (dataWidth side)) :=
  pairs (List.finRange _) (List.finRange _)

def within : List (Entry clauses j copy) :=
  selected (indexPairs side) (fun p => decide (group side p.1 = group side p.2))
    (fun _ => by rw [decide_eq_true_eq]) (fun p same => entry (Request.withinGroup p.1 p.2 same))

def mixed : List (Entry clauses j copy) :=
  selected (indexPairs side) (fun p => decide (p.1 ≠ p.2))
    (fun _ => by rw [decide_eq_true_eq]) (fun p different => entry (Request.mixedData p.1 p.2 different))

 abbrev Triple (side : ℕ) := DataIndex side × DataIndex side × DataIndex side

abbrev TraceRecords (side : ℕ) := DataIndex side → DataIndex side → DataIndex side → NativeRow side

 def triples (side : ℕ) : List (Triple side) :=
  pairs (dataIndices side) (pairs (dataIndices side) (dataIndices side))

 def acceptable (p : Triple side) : Prop :=
  ¬QuarticFreeEntries.IsReal p.1 ∧ dataGroup p.1 ≠ dataGroup p.2.1 ∧
    dataGroup p.1 ≠ dataGroup p.2.2 ∧ dataGroup p.2.1 ≠ dataGroup p.2.2

 def accepts (p : Triple side) : Bool :=
  notRealBit p.1 && (decide (dataGroup p.1 ≠ dataGroup p.2.1) &&
    (decide (dataGroup p.1 ≠ dataGroup p.2.2) && decide (dataGroup p.2.1 ≠ dataGroup p.2.2)))

 theorem accepts_correct (p : Triple side) : accepts p = true ↔ acceptable p := by
  simp only [accepts,Bool.and_eq_true,notRealBit_correct,decide_eq_true_eq,acceptable]

def fixed (trace : TraceRecords side) (agrees : trace = tripleRecord) : List (Entry clauses j copy) :=
  selected (triples side) accepts accepts_correct fun p h =>
    ⟨tripleDirection p.1 p.2.1 p.2.2,⟨trace p.1 p.2.1 p.2.2,by
      rw [agrees]
      exact Request.fixedTriple p.1 p.2.1 p.2.2 h.1 h.2.1 h.2.2.1 h.2.2.2⟩⟩

end RSGPaper.QuarticGuardDataEntries

end

section

set_option autoImplicit false
set_option maxHeartbeats 1650000

namespace RSGPaper.QuarticGuardQuadraticEntries

open QuarticGuardEntries
open QuarticGuardTable
open QuarticGraphSteps
open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticEffectiveSteps
open QuarticEffectiveLinearForms
open QuarticEffectiveGuardTests
open QuarticFirstCorrection (uAxis vAxis wAxis)
open QuarticFirstGuardRows (Output unitDirections)

variable {side : ℕ}
variable (clauses : List (Clause side)) (j : Channel) (copy : Bool)

 abbrev Axis (side : ℕ) := {x : Position side // x ∈ unitDirections (firstWidth side)}

 def unitU (i : Fin (firstWidth side)) : Axis side := ⟨uAxis i,Or.inl (Or.inl ⟨i,rfl⟩)⟩
 def unitV (i : Fin (firstWidth side)) : Axis side := ⟨vAxis i,Or.inl (Or.inr ⟨i,rfl⟩)⟩
 def unitW (side : ℕ) : Axis side := ⟨wAxis (firstWidth side),Or.inr (Set.mem_singleton _)⟩

def unitEntries (side : ℕ) : List (Axis side) :=
  ((List.finRange (firstWidth side)).map unitU ++ (List.finRange (firstWidth side)).map unitV) ++ [unitW side]

def outputs (m : ℕ) : List (Output m) :=
  ((List.finRange m).map Output.u ++ (List.finRange m).map Output.v) ++ [.w]

def firstScalar : List (Entry clauses j copy) :=
  (nativePositions side).map fun x => entry (Request.firstScalar x)

def secondScalar (second : Position side → Position side)
    (agrees : second = QuarticNativeSecond.profile (dataWidth side)) : List (Entry clauses j copy) :=
  (nativePositions side).map fun x => ⟨x,⟨(secondRow (QuarticPrimaryLayout.pairingRow x),QuarticFirstPolar.pairing x (second x)),by
    rw [agrees]
    exact Request.secondScalar x⟩⟩

 def unitPolarBit (axis : Axis side) (i : Output (firstWidth side)) : Bool :=
  (nativePositions side).all (fun y => decide (QuarticFirstGuardRows.row (firstWidth side) i
    (QuarticFirstPolar.polar axis.val y) = 0))

 theorem unitPolarBit_correct (axis : Axis side) (i : Output (firstWidth side)) :
    unitPolarBit axis i = true ↔ ∀ y, QuarticFirstGuardRows.row (firstWidth side) i
      (QuarticFirstPolar.polar axis.val y) = 0 := by
  simp only [unitPolarBit,List.all_eq_true,decide_eq_true_eq]
  exact ⟨fun h y => h y (mem_nativePositions side y),fun h y _ => h y⟩

def firstUnit : List (Entry clauses j copy) :=
  selected (pairs (unitEntries side) (outputs (firstWidth side)))
    (fun p => unitPolarBit p.1 p.2) (fun p => unitPolarBit_correct p.1 p.2)
    (fun p annihilates => entry (Request.firstUnit p.1.val p.1.property p.2 annihilates))

def firstPair : List (Entry clauses j copy) :=
  selected (pairs (List.finRange (firstWidth side)) (List.finRange (firstWidth side)))
    (fun p => decide (p.1 ≠ p.2)) (fun _ => by rw [decide_eq_true_eq])
    (fun p apart => entry (Request.firstPair p.1 p.2 apart))

def secondUnit : List (Entry clauses j copy) :=
  selected (pairs (unitEntries side) (positionForms side)) (fun p => testsSecond p.2)
    (fun p => testsSecond_correct p.2)
    (fun p ann => entry (Request.secondUnit p.1.val p.1.property p.2 ann))

end RSGPaper.QuarticGuardQuadraticEntries

end

section

set_option autoImplicit false
set_option maxHeartbeats 1550000

namespace RSGPaper.QuarticGuardClauseEntries

open QuarticGuardEntries
open QuarticGuardTable
open QuarticGraphSteps
open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticEffectiveLinearForms
open QuarticEffectiveGuardTests
open QuarticCanonicalProfiles

variable {side : ℕ}
variable (clauses : List (Clause side)) (j : Channel) (copy : Bool)

attribute [local irreducible] QuarticAuxJoint.model QuarticAuxJoint.row

abbrev Direction (side : ℕ) := Data side → Position side
abbrev SecondCoupler (side : ℕ) := Data side → (Position side →ₗ[Bit] Bit) → (Position side →ₗ[Bit] Bit)
abbrev AuxiliaryCoupler (side : ℕ) := (u : Data side) → (ℓ : Data side →ₗ[Bit] Bit) →
  QuarticAuxJoint.Ann u ℓ → (Position side →ₗ[Bit] Bit)
abbrev Tensor (side : ℕ) := Data side → Data side → Data side → Data side

def quadratic (direction : Direction side) (dir_agrees : direction = a)
    (couple : SecondCoupler side) (row_agrees : couple = QuarticSecondJoint.row) : List (Entry clauses j copy) :=
  if first : copy = false then
    clauses.attach.flatMap fun c => (positionForms side).map fun ℓ =>
      let u := clauseInput (c.val j)
      ⟨direction u,⟨(secondRow ℓ+firstRow (couple u ℓ),0),by
        rw [dir_agrees,row_agrees]
        exact Request.secondClause c.val c.property first ℓ⟩⟩
  else []

def auxiliaryAt (first : copy = false) (c : {q : Clause side // q ∈ clauses})
    (direction : Direction side) (dir_agrees : direction = a)
    (tensor : Tensor side) (tensor_agrees : tensor = QuarticDataTensor.tensor (QuarticAuxJoint.model side))
    (couple : AuxiliaryCoupler side) (row_agrees : couple = QuarticAuxJoint.row) : List (Entry clauses j copy) :=
  match h : c.val j with
  | none => []
  | some (slot,sign) =>
    let u := literal slot sign
    selected (dataForms side) (testsAux tensor u) (testsAux_correct tensor tensor_agrees u)
      (fun ℓ ann => ⟨direction u,⟨(dataRow (ℓ.comp (QuarticCoreProjection.auxPart side))+
        firstRow (couple u ℓ ann),0),by
          rw [dir_agrees,row_agrees]
          exact Request.auxiliaryClause c.val c.property first slot sign h ℓ ann⟩⟩)

def auxiliary (direction : Direction side) (dir_agrees : direction = a)
    (tensor : Tensor side) (tensor_agrees : tensor = QuarticDataTensor.tensor (QuarticAuxJoint.model side))
    (couple : AuxiliaryCoupler side) (row_agrees : couple = QuarticAuxJoint.row) : List (Entry clauses j copy) :=
  if first : copy = false then clauses.attach.flatMap
    (fun c => auxiliaryAt clauses j copy first c direction dir_agrees tensor tensor_agrees couple row_agrees)
  else []

end RSGPaper.QuarticGuardClauseEntries

end

section

set_option autoImplicit false

noncomputable section

namespace RSGPaper.QuarticGuardReindex

open QuarticGraphSteps
open QuarticGraphColors
open QuarticPalette
open ColorRemovalGraph
open ColorRemovalAction
open ColorRemovalAutomorphisms

variable {d r : Channel → ℕ}

abbrev GuardRows (d r : Channel → ℕ) :=
  (j : Channel) → Bool → Pos (d j) → List ((Lab (r j) →ₗ[Bit] Bit) × Bit)

def replaceGuards (R : Rules d r) (guard : GuardRows d r) : Rules d r := {R with guardRows := guard}

theorem valid_replace (R : Rules d r) (guard : GuardRows d r) (s : Step d) :
    Valid (replaceGuards R guard) s ↔ Valid R s := by
  cases s <;> rfl

end RSGPaper.QuarticGuardReindex

end

section

set_option autoImplicit false
set_option maxHeartbeats 2000000

namespace RSGPaper.QuarticEffectiveGuards

open QuarticGuardEntries
open QuarticGuardTable
open QuarticGraphSteps
open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticCanonicalProfiles
open QuarticEffectiveSteps
open QuarticGuardClauseEntries
open ColorRemovalGraph
open ColorRemovalAction
open ColorRemovalAutomorphisms

variable {side : ℕ}

structure Operations (side : ℕ) where
  second : Position side → Position side
  second_correct : second = QuarticNativeSecond.profile (dataWidth side)
  traces : QuarticGuardDataEntries.TraceRecords side
  traces_correct : traces = tripleRecord
  direction : Direction side
  direction_correct : direction = a
  secondCouple : SecondCoupler side
  secondCouple_correct : secondCouple = QuarticSecondJoint.row
  tensor : Tensor side
  tensor_correct : tensor = QuarticDataTensor.tensor (QuarticAuxJoint.model side)
  auxiliaryCouple : AuxiliaryCoupler side
  auxiliaryCouple_correct : auxiliaryCouple = QuarticAuxJoint.row

def sections (ops : Operations side) (clauses : List (Clause side)) (j : Channel) (copy : Bool) :
    List (List (Entry clauses j copy)) :=
  [QuarticGuardQuadraticEntries.firstScalar clauses j copy,
    QuarticGuardQuadraticEntries.secondScalar clauses j copy ops.second ops.second_correct,
    QuarticGuardQuadraticEntries.firstUnit clauses j copy,
    QuarticGuardQuadraticEntries.firstPair clauses j copy,
    QuarticGuardQuadraticEntries.secondUnit clauses j copy,
    QuarticGuardDataEntries.outside clauses j copy,
    QuarticGuardDataEntries.within clauses j copy,
    QuarticGuardDataEntries.mixed clauses j copy,
    QuarticGuardDataEntries.fixed clauses j copy ops.traces ops.traces_correct,
    quadratic clauses j copy ops.direction ops.direction_correct ops.secondCouple ops.secondCouple_correct,
    auxiliary clauses j copy ops.direction ops.direction_correct ops.tensor ops.tensor_correct
      ops.auxiliaryCouple ops.auxiliaryCouple_correct]

def entries (ops : Operations side) (clauses : List (Clause side)) (j : Channel) (copy : Bool) :
    List (Entry clauses j copy) := (sections ops clauses j copy).flatten

def guardRows (ops : Operations side) (clauses : List (Clause side)) (j : Channel) (copy : Bool)
    (p : Pos (posWidth side)) : List ((Lab (labWidth side) →ₗ[Bit] Bit) × Bit) :=
  rowsAt (entries ops clauses j copy) ((layout side).position p)

end RSGPaper.QuarticEffectiveGuards

end

section

set_option autoImplicit false
set_option maxHeartbeats 1500000

namespace RSGPaper.QuarticCompiledPalette

open QuarticGraphSteps
open QuarticGraphColors
open QuarticPalette
open QuarticEffectiveGuards
open QuarticEffectiveSteps
open QuarticGuardTable
open QuarticChannelLayout
open QuarticCanonicalProfiles
open QuarticVertexNumbers
open QuarticEffectivePalette
open ColorRemovalGraph
open ColorRemovalAction
open ColorRemovalAutomorphisms

variable {side : ℕ}

abbrev VertexAt (side : ℕ) := Vertex (fun _ => posWidth side) (fun _ => labWidth side)

def directions (ops : Operations side) : ClauseDirections side := fun c j =>
  (layout side).position.symm (ops.direction (clauseInput (c j)))

theorem directions_correct (ops : Operations side) : directions ops = clauseDirections := by
  unfold directions
  rw [ops.direction_correct] <;> rfl

private def clauseDirectionsSet (clauses : List (Clause side)) (dirs : ClauseDirections side) :
    Set (Channel → Pos (posWidth side)) := {v | ∃ c ∈ clauses, v = dirs c}

private def rulesAt (clauses : List (Clause side)) (dirs : ClauseDirections side)
    (high : ∀ a ∈ clauseDirectionsSet clauses dirs, ∀ j, QuarticPrimaryLayout.high (layout side) (a j) = 1)
    (guards : QuarticGuardReindex.GuardRows (fun _ => posWidth side) (fun _ => labWidth side)) :
    Rules (fun _ => posWidth side) (fun _ => labWidth side) :=
  QuarticPrimaryLayout.rules (fun _ => layout side) (clauseDirectionsSet clauses dirs) high guards

def rules (ops : Operations side) (clauses : List (Clause side)) : Rules (fun _ => posWidth side) (fun _ => labWidth side) :=
  rulesAt clauses (directions ops) (by unfold clauseDirectionsSet; rw [directions_correct]; exact clause_high clauses)
    (QuarticEffectiveGuards.guardRows ops clauses)

theorem rules_correct (ops : Operations side) (clauses : List (Clause side)) :
    rules ops clauses = QuarticGuardReindex.replaceGuards (QuarticGuardTable.rules clauses)
      (QuarticEffectiveGuards.guardRows ops clauses) := by
  have invariant (dirs : ClauseDirections side) (eq : dirs = clauseDirections)
      (high : ∀ a ∈ clauseDirectionsSet clauses dirs, ∀ j, QuarticPrimaryLayout.high (layout side) (a j) = 1) :
      rulesAt clauses dirs high (QuarticEffectiveGuards.guardRows ops clauses) =
        QuarticGuardReindex.replaceGuards (QuarticGuardTable.rules clauses)
          (QuarticEffectiveGuards.guardRows ops clauses) := by
    subst dirs
    rfl
  exact invariant _ (directions_correct ops) _

instance keyBEq (d : ℕ) : BEq (Key (fun _ => d)) where
  beq x y := equalPositions d x.1 y.1 && (x.2 == y.2)

instance keyLawful (d : ℕ) : LawfulBEq (Key (fun _ => d)) where
  eq_of_beq := by
    intro x y equal
    change (equalPositions d x.1 y.1 && (x.2 == y.2)) = true at equal
    rw [Bool.and_eq_true] at equal
    obtain ⟨left,right⟩ := equal
    exact Prod.ext ((equalPositions_correct d _ _).mp left) (eq_of_beq right)
  rfl := by
    intro x
    change (equalPositions d x.1 x.1 && (x.2 == x.2)) = true
    simp [(equalPositions_correct d _ _).mpr rfl]

def raw (ops : Operations side) (clauses : List (Clause side)) : VertexAt side → Option (Key (fun _ => posWidth side)) :=
  let R := rules ops clauses
  QuarticEffectivePalette.rawFromSteps R (validSteps (directions ops) clauses) (accepts R (validBit (directions ops) clauses))

theorem raw_correct (ops : Operations side) (clauses : List (Clause side)) :
    raw ops clauses = rawColor (rules ops clauses) := by
  let R := rules ops clauses
  have valid (s : StepAt side) : Valid R s ↔ Valid (QuarticGuardTable.rules clauses) s := by
    change Valid (rules ops clauses) s ↔ _
    rw [rules_correct]
    exact QuarticGuardReindex.valid_replace _ _ s
  funext w
  unfold raw
  apply rawFromSteps_correct R
  · intro v s
    exact accepts_correct R _ (fun s => (validBit_correct _ (directions_correct ops) clauses s).trans (valid s).symm) v s
  · intro v s fit
    exact (mem_validSteps _ (directions_correct ops) clauses s).mpr ((valid s).mp fit.1)

def vertexList (side : ℕ) : List (VertexAt side) :=
  vertices (QuarticEffectiveChart.chart (posWidth side) (labWidth side))

theorem raw_zero (ops : Operations side) (clauses : List (Clause side)) : raw ops clauses 0 = none := by
  rw [raw_correct]
  by_contra present
  obtain ⟨s,ok,wrong,_⟩ := (raw_exists _ _).mp present
  exact step_nonzero _ _ ok wrong

def palette (ops : Operations side) (clauses : List (Clause side)) :
    Palette (VertexAt side) (keys (vertexList side) (raw ops clauses)).length :=
  paletteFrom (d := fun _ => posWidth side) (r := fun _ => labWidth side)
    (vertexList side) (raw ops clauses) (raw_zero ops clauses)

end RSGPaper.QuarticCompiledPalette

end

section

set_option autoImplicit false
set_option maxHeartbeats 1400000

namespace RSGPaper.QuarticPaddingMachine

open RSGRecognition
open Turing
open OAI.MetricKMedian.Binary
open OAI.MetricKMedian.Binary.Automatic

abbrev Accumulator := Word × Word
abbrev State := Word × Accumulator

def double (state : Accumulator × Bool) : Accumulator := (state.1.1,state.1.2++state.1.2)

private theorem double_poly : Poly double := by
  unfold double
  fun_prop

noncomputable def program : PolyProgram (enc : State → Word)
    (encodeLoop (enc : State → Word) (enc : Accumulator → Word))
    (ListFold.body false double) :=
  ListFold.program encodeBool (enc : Accumulator → Word) false double double_poly.program

def seed (count original : Word) : State := (count,original,[false])

def result (count original : Word) : Accumulator := (original,List.replicate (2^count.length) false)

def storage (count original : Word) : ℕ := 6*count.length+6*original.length+3*(2^count.length)+2

noncomputable def time (count original : Word) : ℕ := (count.length+1)*program.passTime (storage count original)

end RSGPaper.QuarticPaddingMachine

end

section

set_option autoImplicit false

namespace RSGPaper.SATNormalize

open RSGRecognition
open OAI.MetricKMedian.Binary.Automatic

def unit (value : Bool) : Clause := fun _ => (0, value)

def reject : Formula := [unit false, unit true]

def normalize (w : Word) : Word :=
  if VIGSATParser.canonical w then w else formulaWord reject

theorem normalize_poly : Poly normalize :=
  Poly.ite VIGSATParser.canonical_poly Poly.identity
    (OAI.MetricKMedian.Binary.Automatic.Poly.const (formulaWord reject))

end RSGPaper.SATNormalize

end

section

set_option autoImplicit false
set_option maxHeartbeats 1100000

namespace RSGPaper.QuarticOccurrences

open RSGRecognition

abbrev Occurrence (φ : Formula) := Fin φ.length × Fin 3

def literal {φ : Formula} (p : Occurrence φ) : Literal := φ.get p.1 p.2

def address {φ : Formula} (p : Occurrence φ) : ℕ := 3 * p.1.val + p.2.val

theorem address_injective (φ : Formula) : Function.Injective (@address φ) := by
  rintro ⟨i,a⟩ ⟨j,b⟩ equal
  change 3*i.val + a.val = 3*j.val + b.val at equal
  have left : i.val = j.val := by omega
  have right : a.val = b.val := by omega
  exact Prod.ext (Fin.ext left) (Fin.ext right)

def Linked {φ : Formula} (p q : Occurrence φ) : Prop :=
  address p < address q ∧ (literal p).1 = (literal q).1 ∧
    ∀ r : Occurrence φ, address p < address r → address r < address q → (literal r).1 ≠ (literal p).1

def conflict (φ : Formula) : SimpleGraph (Occurrence φ) where
  Adj p q := p ≠ q ∧ (p.1 = q.1 ∨ Linked p q ∨ Linked q p)
  symm := ⟨by
    intro p q edge
    rcases edge with ⟨ne,same | forward | backward⟩
    · exact ⟨ne.symm,Or.inl same.symm⟩
    · exact ⟨ne.symm,Or.inr (Or.inr forward)⟩
    · exact ⟨ne.symm,Or.inr (Or.inl backward)⟩⟩
  loopless := ⟨fun _ edge => edge.1 rfl⟩

end RSGPaper.QuarticOccurrences

end

section

set_option autoImplicit false
set_option maxHeartbeats 1750000

noncomputable section

namespace RSGPaper.QuarticSATWidth

open RSGRecognition
open QuarticOccurrences
open QuarticChannelLayout

 theorem side_exists (φ : Formula) : ∃ d : ℕ, 3 ≤ d ∧ 3*φ.length ≤ d^4 := by
  let d := 3*φ.length+3
  have positive : 0 < d := by omega
  refine ⟨d,by omega,?_⟩
  calc
    3*φ.length ≤ d := by omega
    _ = d^1 := (pow_one d).symm
    _ ≤ d^4 := Nat.pow_le_pow_right positive (by decide)

def side (φ : Formula) : ℕ := Nat.find (side_exists φ)

theorem enough (φ : Formula) : 3 ≤ side φ ∧ 3*φ.length ≤ (side φ)^4 :=
  Nat.find_spec (side_exists φ)

theorem occurrence_bound {φ : Formula} (p : Occurrence φ) : address p < 3*φ.length := by
  have first := p.1.isLt
  have second := p.2.isLt
  unfold address
  omega

def slots (φ : Formula) : Occurrence φ ↪ Slot (side φ) :=
  let rank (p : Occurrence φ) : Fin ((side φ)^4) := ⟨address p,(occurrence_bound p).trans_le (enough φ).2⟩
  let E := QuarticFiniteIndex.functionIndex (side φ) 4
  ⟨fun p => E.symm (rank p),fun p q equal => address_injective φ (congrArg Fin.val (E.symm.injective equal))⟩

end RSGPaper.QuarticSATWidth

end

section

set_option autoImplicit false
set_option maxHeartbeats 1200000

namespace RSGPaper.QuarticPaddingInput

open RSGRecognition
open QuarticSATWidth
open QuarticPaddingMachine
open VIGSATParser
open EIGNumericRuntime
open OAI.MetricKMedian.Binary
open OAI.MetricKMedian.Binary.Automatic
open QMCNumericRuntime (parser_take_poly)

def searchFuel (cs : Clauses) : Word := scaleTwo 2 (false::cs.map (fun _ => false))

@[fun_prop] theorem searchFuel_poly : Poly searchFuel := by
  unfold searchFuel
  fun_prop

def accepts (m d : ℕ) : Bool := decide (3 ≤ d) && decide (3*m ≤ d^4)

@[fun_prop] theorem accepts_poly : Poly (fun x : ℕ × ℕ => accepts x.1 x.2) := by
  simp only [accepts,pow_succ,pow_zero,one_mul]
  fun_prop

def chosen (cs : Clauses) : ℕ := (List.range (searchFuel cs).length).findIdx (accepts cs.length)

@[fun_prop] theorem chosen_poly : Poly chosen := by
  have test : Poly (fun x : Clauses × ℕ => accepts x.1.length x.2) :=
    accepts_poly.comp ((Poly.list_length.comp Poly.fst).pair Poly.snd)
  exact Poly.list_findIdx (f := fun cs i => accepts cs.length i) test (Poly.list_indices.comp searchFuel_poly)

def tokens (cs : Clauses) : Word := scaleTwo 20 (false::(searchFuel cs).take (chosen cs))

@[fun_prop] theorem tokens_poly : Poly tokens := by
  unfold tokens
  exact (scaleTwo_poly 20).comp (Poly.list_cons.comp
    ((Automatic.Poly.const false).pair (parser_take_poly.comp (searchFuel_poly.pair chosen_poly))))

end RSGPaper.QuarticPaddingInput

end

section

set_option autoImplicit false

namespace RSGPaper.TimeEnvelope

open RSGRecognition

noncomputable def base (e : ℝ) (w : Word) : ℝ :=
  (2 : ℝ) ^ ((threeSATSize w : ℝ) + 1) ^ e * ((w.length : ℝ) + 1)

def Bounded (e : ℝ) (t : Word → ℝ) : Prop := ∃ C : ℕ, ∀ w, t w ≤ base e w ^ C

end RSGPaper.TimeEnvelope

end

section

set_option autoImplicit false
set_option maxHeartbeats 1400000

namespace RSGPaper.QuarticPaddingPipeline

open RSGRecognition
open QuarticPaddingMachine
open QuarticPaddingInput
open QuarticSATWidth
open OAI.MetricKMedian.Binary
open OAI.MetricKMedian.Binary.Automatic

def count (w : Word) : Word := tokens (VIGSATParser.parse (SATNormalize.normalize w))

attribute [local irreducible] formulaSize threeSATSize

def preprocessed (w : Word) : State := seed (count w) w

noncomputable def prepCode : PolyProgram id (enc : State → Word) preprocessed := by
  have countPoly : Poly count := tokens_poly.comp (VIGSATParser.parse_poly.comp SATNormalize.normalize_poly)
  have prep : Poly preprocessed := countPoly.pair (Poly.identity.pair (Automatic.Poly.const [false]))
  exact BooleanLists.packProgram.comp prep.program

def padded (w : Word) : Accumulator := result (count w) w

noncomputable def inputEncoder (w : Word) : Word := enc (preprocessed w)

end RSGPaper.QuarticPaddingPipeline

end

section

set_option autoImplicit false

namespace RSGPaper.QuarticProfileMatrix

open QuarticGraphSteps
open QuarticGraphColors
open QuarticProfileKernel
open QuarticRootAction
open EIGLinearSystem
open QuarticFiniteIndex
open QuarticVertexNumbers

abbrev Address (d r : Channel → ℕ) := Σ i : Factor, Pos (width d i) × Fin (width r i)

private def addressBlocks (d r : ℕ) : Address (fun _ => d) (fun _ => r) ≃
    ((Channel × Bool) × (Pos d × Fin r)) ⊕ (Bool × Pos 1) where
  toFun
    | ⟨.inl q,p,j⟩ => .inl (q,p,j)
    | ⟨.inr q,p,_⟩ => .inr (q,p)
  invFun
    | .inl (q,p,j) => ⟨.inl q,p,j⟩
    | .inr (q,p) => ⟨.inr q,p,0⟩
  left_inv := by
    rintro ⟨i,p,k⟩
    rcases i with i|i
    · rfl
    · have same : k = 0 := Subsingleton.elim _ _
      subst k
      rfl
  right_inv := by rintro (⟨q,p,j⟩|⟨q,p⟩) <;> rfl

def tableWidth (d r : ℕ) := 14*(2^d*r)+4

def codedAddresses (d r : ℕ) : Address (fun _ => d) (fun _ => r) ≃ Fin (tableWidth d r) :=
  let channels : Channel × Bool ≃ Fin 14 := ((Equiv.refl _).prodCongr binaryIndex).trans finProdFinEquiv
  let primary : Pos d × Fin r ≃ Fin (2^d*r) := ((cubeIndex d).prodCongr (Equiv.refl _)).trans finProdFinEquiv
  let main : (Channel × Bool) × (Pos d × Fin r) ≃ Fin (14*(2^d*r)) :=
    (channels.prodCongr primary).trans finProdFinEquiv
  let extras : Bool × Pos 1 ≃ Fin 4 := (binaryIndex.prodCongr (cubeIndex 1)).trans finProdFinEquiv
  ((addressBlocks d r).trans (main.sumCongr extras)).trans finSumFinEquiv

variable {d r : Channel → ℕ} {n : ℕ}

def table (E : Address d r ≃ Fin n) : Profiles d r ≃ₗ[Bit] (Fin n → Bit) where
  toFun f k := let j := E.symm k; f j.1 j.2.1 j.2.2
  invFun z i p k := z (E ⟨i,p,k⟩)
  left_inv f := by
    funext i p k
    change (let j := E.symm (E ⟨i,p,k⟩); f j.1 j.2.1 j.2.2) = f i p k
    rw [Equiv.symm_apply_apply]
  right_inv z := by
    funext i
    exact congrArg z (E.apply_symm_apply i)
  map_add' _ _ := rfl
  map_smul' _ _ := rfl

def equation (E : Address d r ≃ Fin n) (R : Rules d r) (s : Step d) (p : Positions d)
    (ℓ : Labels r →ₗ[Bit] Bit) : Equation n :=
  (ℓ.comp ((labelDifference p (p+position R s)).comp (table E).symm.toLinearMap),0)

def equations (E : Address d r ≃ Fin n) (R : Rules d r) (steps : List (Step d))
    (points : List (Positions d)) : List (Equation n) :=
  steps.flatMap fun s => points.flatMap fun p => (rowMaps R s).map (equation E R s p)

end RSGPaper.QuarticProfileMatrix

end

section

set_option autoImplicit false
set_option maxHeartbeats 1450000

namespace RSGPaper.QuarticGraphSize

open QuarticGraphSteps
open QuarticGraphColors
open QuarticPalette
open QuarticColoredChart
open QuarticChannelLayout

def coloredExponent (side : ℕ) : ℕ := 518*dataWidth side+802

end RSGPaper.QuarticGraphSize

end

section

set_option autoImplicit false
set_option maxHeartbeats 1200000

namespace RSGPaper.QuarticCompilerSizes

open RSGRecognition
open EIGNumericRuntime
open QuarticSATWidth
open QuarticPaddingPipeline
open QuarticChannelLayout
open QuarticGraphSize
open QuarticCanonicalProfiles
open OAI.MetricKMedian.Binary.Automatic
open QMCNumericRuntime (parser_take_poly)

def cap (fuel : Word) (k : ℕ) : ℕ := powerOfTwo (fuel.take k)

def blocks (side : ℕ) : ℕ := coloredExponent side

def labelWidthRaw (side : ℕ) : ℕ := 16*blocks side

def posWidthRaw (side : ℕ) : ℕ := posWidth side

def labWidthRaw (side : ℕ) : ℕ := labWidth side

def labelFuel (fuel : Word) (side : ℕ) : Word := fuel.take (cap fuel (labelWidthRaw side))

def tableFuel (fuel : Word) (side : ℕ) : Word :=
  fuel.take (14*(cap fuel (posWidthRaw side)*labWidthRaw side)+4)

end RSGPaper.QuarticCompilerSizes

end

section

set_option autoImplicit false

namespace RSGPaper.QuarticEffectiveColoring

open RSGRecognition
open QuarticOccurrences

def occurrences (φ : Formula) : List (Occurrence φ) :=
  List.ofFn (finProdFinEquiv (m := φ.length) (n := 3)).symm

theorem mem_occurrences {φ : Formula} (p : Occurrence φ) : p ∈ occurrences φ :=
  List.mem_ofFn.mpr ⟨finProdFinEquiv p,finProdFinEquiv.symm_apply_apply p⟩

def linkedBit {φ : Formula} (p q : Occurrence φ) : Bool :=
  decide (address p < address q) && decide ((literal p).1 = (literal q).1) &&
    (occurrences φ).all (fun r => !(decide (address p < address r) &&
      decide (address r < address q) && decide ((literal r).1 = (literal p).1)))

theorem linkedBit_true {φ : Formula} (p q : Occurrence φ) : linkedBit p q = true ↔ Linked p q := by
  simp only [linkedBit,Bool.and_eq_true,decide_eq_true_eq,List.all_eq_true,Bool.not_eq_true',
    Bool.and_eq_false_imp,List.mem_iff_get]
  constructor
  · rintro ⟨⟨low,same⟩,all⟩
    refine ⟨low,same,fun r pr rq vr => ?_⟩
    have hr := all r (List.mem_iff_get.mp (mem_occurrences r))
    simp [pr,rq,vr] at hr
  · rintro ⟨low,same,all⟩
    refine ⟨⟨low,same⟩,fun r _ => ?_⟩
    by_cases pr : address p < address r <;> by_cases rq : address r < address q <;> simp_all

def linkedDecidable {φ : Formula} (p q : Occurrence φ) : Decidable (Linked p q) :=
  decidable_of_iff (linkedBit p q = true) (linkedBit_true p q)

@[instance_reducible] def conflictDecidable (φ : Formula) : DecidableRel (conflict φ).Adj := fun p q => by
  change Decidable (p ≠ q ∧ (p.1 = q.1 ∨ Linked p q ∨ Linked q p))
  letI : Decidable (Linked p q) := linkedDecidable p q
  letI : Decidable (Linked q p) := linkedDecidable q p
  infer_instance

def links (φ : Formula) : List (Occurrence φ × Occurrence φ) :=
  (occurrences φ).flatMap fun p =>
    ((occurrences φ).filter (linkedBit p)).map fun q => (p,q)

section Greedy

variable {V : Type} [DecidableEq V] (G : SimpleGraph V) [DecidableRel G.Adj]
variable {q : ℕ} (positive : 0 < q)

def used (x : V) (tail : List V) (f : V → Fin q) : List (Fin q) :=
  (tail.filter fun y => decide (G.Adj x y)).map f

def pick (colors : List (Fin q)) : Fin q :=
  ((List.finRange q).find? fun i => !(colors.contains i)).getD ⟨0,positive⟩

def paint : List V → V → Fin q
  | [] => fun _ => ⟨0,positive⟩
  | x::xs =>
    let tail := paint xs
    Function.update tail x (pick positive (used G x xs tail))

end Greedy

def occurrenceColor (φ : Formula) : Occurrence φ → Fin 5 :=
  letI := conflictDecidable φ
  paint (conflict φ) (by decide) (occurrences φ)

end RSGPaper.QuarticEffectiveColoring

end

section

set_option autoImplicit false
set_option maxHeartbeats 1250000

namespace RSGPaper.QuarticEffectiveDirections

open BooleanMonomials
open QuarticBinaryField
open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticNativeSecond
open QuarticFieldCoordinates
open QuarticGuardTable
open QuarticEffectiveSteps

variable {side : ℕ}

 abbrev degree (side : ℕ) := fieldWidth (dataWidth side)

private theorem positive (side : ℕ) : 0 < degree side := by
  unfold degree fieldWidth
  omega

def padded {side : ℕ} (x : Data side) : Cube (degree side) :=
  (splitCube (dataWidth side) (dataWidth side+3)).symm (x,0)

def tailWord {side : ℕ} (x : Data side) : QuarticBinaryField.Word (degree side) :=
  let j := wordOfBits (padded x)
  let b := wordOfBits (padded (QuarticClauseBit.excludeGroup (group side) 0 x))
  wordAdd (wordSquarefree j) (wordPolar j b)

def input {side : ℕ} (x : Data side) : U side :=
  (blocks (dataWidth side)).symm (padded x,0,wordBits (tailWord x))

theorem coordinate_word {d : ℕ} (pos : 0 < d) (x : QuarticBinaryField.Word d) :
    coordinates d pos.ne' (wordBits x) = fieldValue pos x := by
  unfold coordinates
  rw [basis_is_effective]
  change (fieldBasis d pos).equivFun.symm (wordBits x) = _
  rw [← fieldBasis_read pos x,LinearEquiv.symm_apply_apply]

private theorem field_of_padded (x : Data side) :
    fieldValue (positive side) (wordOfBits (padded x)) = dataField x := by
  rw [← coordinate_word,wordBits_wordOfBits]
  rfl

private theorem polar_expanded {F : Type} [Field F] [CharP F 2] [Algebra (ZMod 2) F]
    (a b : F) : QuarticSecondPolar.fieldPolar a b = a^2*b+a*b^2 := by
  change QuarticField.cubicPolar a b = _
  unfold QuarticField.cubicPolar
  ring

theorem tail_correct (x : Data side) :
    fieldValue (positive side) (tailWord x) =
      QuarticSecondPolar.squarefreePart (removeLinearCube (degree side) (positive side).ne') (dataField x) +
      QuarticSecondPolar.fieldPolar (dataField x) (dataField (QuarticClauseBit.excludeGroup (group side) 0 x)) := by
  simp only [tailWord,fieldValue_add,fieldValue_squarefree,fieldValue_polar,field_of_padded,
    QuarticSecondPolar.squarefreePart,removeLinearCube,basis_is_effective,polar_expanded]

theorem input_correct (x : Data side) : input x = firstInput x := by
  apply (positionFields (dataWidth side)).injective
  rw [firstFields]
  unfold input positionFields
  rw [LinearEquiv.trans_apply,LinearEquiv.apply_symm_apply]
  apply Prod.ext
  · rfl
  · apply Prod.ext
    · change dualCoordinates (degree side) (positive side).ne' 0 = 0
      exact map_zero (dualCoordinates (degree side) (positive side).ne')
    · change coordinates (degree side) (positive side).ne' (wordBits (tailWord x)) = _
      rw [coordinate_word]
      exact tail_correct x

end RSGPaper.QuarticEffectiveDirections

end

section

set_option autoImplicit false
set_option maxHeartbeats 1250000

namespace RSGPaper.QuarticEffectiveModel

open QuarticBinaryField
open QuarticSliceCoefficients
open QuarticSliceLayout
open QuarticChannelLayout
open QuarticLiteralDirection
open QuarticGuardTable
open QuarticGuardClauseEntries
open QuarticFirstPolar
open QuarticFieldCoordinates
open CubicGauge

variable {side : ℕ}

def coefficient (term : SliceTerm side) : ZMod 2 :=
  traceCoefficient term.squared term.aux term.left term.right

theorem coefficient_correct (term : SliceTerm side) : coefficient term = traceValue term := by
  unfold coefficient traceValue coreBasis
  rw [basis_is_effective]
  exact traceCoefficient_correct (Nat.succ_pos side) term.squared term.aux term.left term.right

def fixed (support : Finset (DataIndex side)) : ZMod 2 :=
  ∑ term : SliceTerm side, if sliceSupport term = support then coefficient term else 0

theorem fixed_correct (support : Finset (DataIndex side)) : fixed support = fixedQuartic support := by
  exact Finset.sum_congr rfl fun term _ => by simp only [coefficient_correct]

def model (side : ℕ) : QuarticSliceRead.Potential side := fun support =>
  let named := support.map (index side).symm.toEmbedding
  fixedCubic side named + fixed named

theorem model_correct (side : ℕ) : model side = QuarticAuxJoint.model side := by
  funext support
  unfold model QuarticAuxJoint.model potential channelCoefficients
  dsimp only
  rw [fixed_correct]
  have zero (s : Finset (DataIndex side)) : realQuartic (0 : Slot side → ZMod 2) s = 0 := by
    simp [realQuartic]
  rw [zero,add_zero]

def tensor (side : ℕ) : Tensor side := QuarticDataTensor.tensor (model side)

theorem tensor_correct (side : ℕ) : tensor side = QuarticDataTensor.tensor (QuarticAuxJoint.model side) := by
  rw [tensor,model_correct]

def triple (i j l : DataIndex side) : NativeRow side :=
  let I := index side i
  let J := index side j
  let L := index side l
  let dir := tripleDirection i j l
  let ρ := QuarticGuardRows.explicitRow
    ((QuarticTripleRows.linearRow (model side) I J L).comp (QuarticProjectedData.read side))
  (dataRow (dotLinear (QuarticProjectedData.read side dir))+firstRow ρ,
    model side {L,J,I}+ρ (firstProfile side dir))

theorem triple_correct (side : ℕ) : @triple side = @tripleRecord side := by
  funext i j l
  unfold triple
  simp only [model_correct]
  rfl

def auxiliary (side : ℕ) : AuxiliaryCoupler side := fun u ℓ ann =>
  QuarticGuardRows.explicitRow
    ((QuarticAuxSlope.slope (model side) u ℓ (by rw [model_correct]; exact ann)).comp (QuarticProjectedData.read side))

theorem auxiliary_correct (side : ℕ) : auxiliary side = @QuarticAuxJoint.row side := by
  funext u ℓ ann
  apply DFunLike.ext
  intro x
  let read := QuarticProjectedData.read side (QuarticGuardRows.swapClear x)
  change QuarticAuxSlope.measured (model side) u ℓ read+QuarticAuxSlope.measured (model side) u ℓ 0 =
    QuarticAuxSlope.measured (QuarticAuxJoint.model side) u ℓ read+
      QuarticAuxSlope.measured (QuarticAuxJoint.model side) u ℓ 0
  rw [model_correct]

end RSGPaper.QuarticEffectiveModel

end

section

set_option autoImplicit false
set_option maxHeartbeats 1850000

namespace RSGPaper.QuarticEffectiveSecond

open BooleanMonomials
open CubicGauge
open QuarticChannelLayout
open QuarticNativeSecond
open QuarticFieldCoordinates
open QuarticBinaryField
open QuarticEffectiveDirections
open QuarticGuardClauseEntries
open QuarticSecondCorrection (Native)

private theorem width_pos (data : ℕ) : 0 < width data := by
  unfold width fieldWidth
  omega

def dualWord (d : ℕ) (j a : Cube d) : Cube d :=
  fun i => dot (wordBits (wordPolar (wordOfBits j) (unitWord i))) a

def secondWord (d : ℕ) (j z : Cube d) : Cube d := wordBits (wordSquarefree (wordOfBits j))+z

def profile (data : ℕ) (x : Native data) : Native data :=
  let coords := blocks data x.1
  ((blocks data).symm (dualWord (width data) coords.1 coords.2.1,secondWord (width data) coords.1 coords.2.2,0),0,0)

private theorem coord_input {d : ℕ} (positive : 0 < d) (x : Cube d) :
    fieldValue positive (wordOfBits x) = coordinates d positive.ne' x := by
  unfold coordinates
  rw [basis_is_effective]
  exact fieldValue_bits positive x

private theorem unitBits {d : ℕ} (i : Fin d) : wordBits (unitWord i) = e i := by
  funext k
  by_cases same : k = i
  · simp [wordBits,unitWord,bitValue,e,indicator,same]
  · simp [wordBits,unitWord,bitValue,e,indicator,same]

theorem dual_correct {d : ℕ} (positive : 0 < d) (j a : Cube d) :
    dualCoordinates d positive.ne' (dualWord d j a) =
      (dualCoordinates d positive.ne' a).comp (QuarticSecondPolar.fieldPolar (coordinates d positive.ne' j)) := by
  apply (fieldBasis d positive).ext
  intro i
  have unitRead : coordinates d positive.ne' (wordBits (unitWord i)) = fieldBasis d positive i := by
    rw [coordinate_word,fieldValue_unit]
  have at_basis := dual_evaluate d positive.ne' (wordBits (unitWord i)) (dualWord d j a)
  rw [unitRead,unitBits,QuarticDataTensor.dot_basis] at at_basis
  rw [at_basis]
  change dot (wordBits (wordPolar (wordOfBits j) (unitWord i))) a =
    dualCoordinates d positive.ne' a
      (QuarticSecondPolar.fieldPolar (coordinates d positive.ne' j) (fieldBasis d positive i))
  rw [← dual_evaluate d positive.ne',coordinate_word positive,fieldValue_polar positive,
    coord_input positive,fieldValue_unit positive]
  congr 1
  change (coordinates d positive.ne' j)^2*fieldBasis d positive i +
    coordinates d positive.ne' j*(fieldBasis d positive i)^2 = QuarticField.cubicPolar _ _
  unfold QuarticField.cubicPolar
  ring

theorem second_correct {d : ℕ} (positive : 0 < d) (j z : Cube d) :
    coordinates d positive.ne' (secondWord d j z) =
      QuarticSecondPolar.squarefreePart (removeLinearCube d positive.ne') (coordinates d positive.ne' j)+
        coordinates d positive.ne' z := by
  rw [secondWord,map_add,coordinate_word positive,fieldValue_squarefree positive,coord_input positive]
  simp only [QuarticSecondPolar.squarefreePart,removeLinearCube,basis_is_effective]

theorem profile_correct (data : ℕ) : profile data = QuarticNativeSecond.profile data := by
  funext x
  let d := width data
  let b := blocks data x.1
  let raw := (blocks data).symm (dualWord d b.1 b.2.1,secondWord d b.1 b.2.2,0)
  have gradient : outputFields data raw = QuarticSecondPolar.secondProfile (removeLinearCube d (width_pos data).ne')
      (projection data x) := by
    unfold outputFields
    rw [LinearEquiv.trans_apply]
    unfold raw
    rw [LinearEquiv.apply_symm_apply]
    apply Prod.ext
    · exact dual_correct (width_pos data) b.1 b.2.1
    · apply Prod.ext
      · exact second_correct (width_pos data) b.1 b.2.2
      · exact map_zero (coordinates d (width_pos data).ne')
  calc
    profile data x = embedding data (outputFields data raw) := by
      change (raw,0,0) = ((outputFields data).symm (outputFields data raw),0,0)
      rw [LinearEquiv.symm_apply_apply]
    _ = QuarticNativeSecond.profile data x := congrArg (embedding data) gradient

private theorem profile_polar_read (data : ℕ) (a x : Native data) :
    profile data (x+a)+profile data x+profile data a = QuarticSecondCorrection.nativePolar data a x := by
  rw [profile_correct]
  have h := QuarticSecondCorrection.canonical_difference data a x
  unfold QuarticJointGuards.delta at h
  rw [h]
  rw [add_comm (QuarticNativeSecond.profile data a),add_assoc,QuarticCayley.double,add_zero]

def polarAt (data : ℕ) (a : Native data) : Native data →ₗ[Bit] Native data where
  toFun x := profile data (x+a)+profile data x+profile data a
  map_add' x y := by simp only [profile_polar_read,map_add]
  map_smul' k x := by simp only [profile_polar_read,map_smul,RingHom.id_apply]

theorem polarAt_correct (data : ℕ) (a : Native data) : polarAt data a = QuarticSecondCorrection.nativePolar data a :=
  DFunLike.ext _ _ (profile_polar_read data a)

def coupler (side : ℕ) : SecondCoupler side := fun u ℓ =>
  QuarticGuardRows.explicitRow (ℓ.comp (polarAt (dataWidth side) (input u,0,1)))

theorem coupler_correct (side : ℕ) : coupler side = @QuarticSecondJoint.row side := by
  funext u ℓ
  unfold coupler
  rw [input_correct,polarAt_correct] <;> rfl

end RSGPaper.QuarticEffectiveSecond

end
Source
Sirawit Pongnakintr, Riemannian Symmetric Graphs, Hexagon v2 preprint, https://hexagonmath.org/2611.01261v2, Theorem 5.2 and Appendix A.5

View graph

Get started

Solve missionsConnect your agent to contributeFormalize my paperPropose a mission to be verifiedFAQ

About Prove2Me

Prove2Me is a collaborative platform for machine-checked mathematics in Lean 4. Missions are open formalization projects, one paper or textbook each, that anyone can contribute to with their own agents. Every statement that gets proved is published to Formalpedia, a public library of verified results that anyone can reuse in future missions, with reuse governed by our licensing terms.

How Prove2Me worksResearch paperProve2Me Team
SKILL.mdTourFAQContactTerms
© 2026 Prove2Me