Characteristic tables for the Bodlaender–Kloks treewidth algorithm
DefinitionBodlaenderKloks_CharacteristicTablesalgorithmsgraph-theorytreewidth
Rooted decompositions, nice decompositions and characteristic trees encode partial solutions on a bag. The definitions include typical sequences, domination, introduction plans, table transitions and the predicates for valid partial decompositions. These are the objects shared by the correctness and reconstruction proofs.
Definition code
import Definitions.Def_EdgeSublinearMWIS_Main_NativeSchemeInterfaces
import Definitions.Def_EdgeSublinearMWIS_Main_NativeWordRAM
import Definitions.Def_Lax228581_Treewidth
import Definitions.Def_Lax689794_GraphWords
import Mathlib.Algebra.BigOperators.Group.Finset.Sigma
import Mathlib.Algebra.BigOperators.Intervals
import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Combinatorics.SimpleGraph.Acyclic
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
import Mathlib.Combinatorics.SimpleGraph.Maps
import Mathlib.Combinatorics.SimpleGraph.Metric
import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Image
import Mathlib.Data.Finset.Option
import Mathlib.Data.Finset.Powerset
import Mathlib.Data.Finset.Sigma
import Mathlib.Data.Finset.Sort
import Mathlib.Data.Finset.Sum
import Mathlib.Data.Finset.Union
import Mathlib.Data.List.Basic
import Mathlib.Data.List.Dedup
import Mathlib.Data.List.Forall2
import Mathlib.Data.List.GetD
import Mathlib.Data.List.Induction
import Mathlib.Data.List.Sort
import Mathlib.Data.List.Sublists
import Mathlib.Data.Nat.Lattice
import Mathlib.Data.Set.Basic
import Mathlib.Data.Set.Card
import Mathlib.Logic.Relation
import Mathlib.Order.Interval.Finset.Nat
import Mathlib.Tactic
set_option autoImplicit false
set_option maxRecDepth 12000
set_option maxHeartbeats 3200000
-- Lax689794Proofs.Trees.Basic
section SourceModule0
/-!
# Decompositions as inductive rooted trees, nice trees (definitions; the two bridges live in `Trees/Bridge1`, `Trees/Bridge2`)
**Representation decision (PLAN §a).** All the algorithmic mathematics lives on *inductive rooted trees with
`Finset ℕ` bags* (`RT`), and on *nice trees* (`NT`). Validity is a recursive predicate (no `SimpleGraph` tree
structure, no node types). There are exactly two bridges, both proved once and used only at the two ends:
* `RT ↔ Lax228581.Treewidth.TreeDecomposition` (`hasTreewidthAtMost_iff_rt`) — the *statement* of the
concept (`¬ HasTreewidthAtMost` for the negative answer);
* `NT ↔ GraphWords.NiceDecomposition` (`niceDecomposition_encode`, `niceDecomposition_parse`) — the
*word format* of input and output.
Every vertex is a natural number; a graph on `Fin n` is lifted along `Fin.val`.
-/
namespace Lax689794Proofs.Trees
open Lax228581.Treewidth
/-! ## rooted decomposition trees -/
set_option genInjectivity false in
/-- A rooted tree of bags (arbitrary arity). -/
inductive RT where
| node (bag : Finset ℕ) (kids : List RT)
namespace RT
def rootBag : RT → Finset ℕ
| node b _ => b
mutual
/-- All vertices occurring in the tree. -/
def verts : RT → Finset ℕ
| node b ks => b ∪ vertsL ks
def vertsL : List RT → Finset ℕ
| [] => ∅
| k :: ks => verts k ∪ vertsL ks
end
mutual
/-- The bags of all nodes. -/
def bags : RT → List (Finset ℕ)
| node b ks => b :: bagsL ks
def bagsL : List RT → List (Finset ℕ)
| [] => []
| k :: ks => bags k ++ bagsL ks
end
mutual
/-- *Connectedness of the occurrence sets*, recursively: a vertex of a bag that occurs below a child occurs in the
child's root bag; a vertex not in the bag occurs below at most one child. -/
def Conn : RT → Prop
| node b ks => ConnL ks ∧ (∀ k ∈ ks, ∀ v ∈ b, v ∈ verts k → v ∈ rootBag k) ∧
ks.Pairwise (fun k₁ k₂ => ∀ v, v ∈ verts k₁ → v ∈ verts k₂ → v ∈ b)
def ConnL : List RT → Prop
| [] => True
| k :: ks => Conn k ∧ ConnL ks
end
/-- `t` is a tree decomposition of the subgraph of `G` induced on `U`. -/
structure IsTD (G : SimpleGraph ℕ) (U : Finset ℕ) (t : RT) : Prop where
verts_eq : t.verts = U
edges : ∀ u v, G.Adj u v → u ∈ U → v ∈ U → ∃ X ∈ t.bags, u ∈ X ∧ v ∈ X
conn : t.Conn
/-- All bags have at most `w + 1` elements. -/
def Width (t : RT) (w : ℕ) : Prop := ∀ X ∈ t.bags, X.card ≤ w + 1
end RT
/-! ## nice trees -/
set_option genInjectivity false in
set_option genSizeOfSpec false in
/-- Nice decompositions: leaf, introduce, forget, join. (Bags are *computed*, as in the word format.) -/
inductive NT where
| leaf
| intro (v : ℕ) (c : NT)
| forget (v : ℕ) (c : NT)
| join (a b : NT)
namespace NT
/-- The bag of the root. -/
def bag : NT → Finset ℕ
| leaf => ∅
| intro v c => insert v (bag c)
| forget v c => (bag c).erase v
| join a _ => bag a
/-- Shape conditions: the introduced vertex is new, the forgotten one is present, joins have equal bags. -/
def Wf : NT → Prop
| leaf => True
| intro v c => v ∉ bag c ∧ Wf c
| forget v c => v ∈ bag c ∧ Wf c
| join a b => bag a = bag b ∧ Wf a ∧ Wf b
/-- The underlying decomposition tree. -/
def toRT : NT → RT
| leaf => .node ∅ []
| intro v c => .node (bag (intro v c)) [toRT c]
| forget v c => .node (bag (forget v c)) [toRT c]
| join a b => .node (bag a) [toRT a, toRT b]
/-- `t` is a nice decomposition of `G[U]` of width `≤ w`. -/
def IsNiceTD (G : SimpleGraph ℕ) (U : Finset ℕ) (t : NT) (w : ℕ) : Prop :=
t.Wf ∧ t.toRT.IsTD G U ∧ t.toRT.Width w
/-- Number of nodes. -/
def size : NT → ℕ
| leaf => 1
| intro _ c => size c + 1
| forget _ c => size c + 1
| join a b => size a + size b + 1
/-- Insert the vertex `v` into every bag: an introduce node above every leaf (this is *the* word
transformation of the wrapper, PLAN §e). -/
def addEverywhere (v : ℕ) : NT → NT
| leaf => intro v leaf
| intro u c => intro u (addEverywhere v c)
| forget u c => forget u (addEverywhere v c)
| join a b => join (addEverywhere v a) (addEverywhere v b)
/-! ### The word format (`GraphWords`) -/
/-- One record `(kind, vertex, other)` per node, children before parents; the first child of a node is the node just
before it, the second child of a join is `other`. `recs b t` numbers the nodes from `b`. -/
def recs : ℕ → NT → List (ℕ × ℕ × ℕ)
| _, leaf => [(0, 0, 0)]
| b, intro v c => recs b c ++ [(1, v, 0)]
| b, forget v c => recs b c ++ [(2, v, 0)]
| b, join x y =>
let ry := recs b y
let rx := recs (b + ry.length) x
ry ++ rx ++ [(3, 0, b + ry.length - 1)]
/-- The word `N` followed by `N` records. -/
def encode (t : NT) : List ℕ :=
let rs := recs 0 t
rs.length :: rs.flatMap (fun r => [r.1, r.2.1, r.2.2])
end NT
end Lax689794Proofs.Trees
end SourceModule0
-- Lax689794Proofs.Seq.Stack
section SourceModule3
/-! ### `Lax689794Proofs.Seq.Basic` -/
section
/-!
# Typical sequences (Bodlaender–Kloks, §3): the two reduction operations
Integer sequences are `List ℕ`. This file defines the two operations of Def. 3.5
(remove a consecutive repetition; the *typical operation*) as one reduction step `Red`,
its reflexive-transitive closure `Reach`, the normal forms `NF` ("no operation possible
any more"), and an index view (`Dup`, `Win`) of the same notions.
-/
namespace Lax689794Proofs.Seq
/-- `z` lies in the closed interval spanned by `x` and `y`. -/
def InR (z x y : ℕ) : Prop := min x y ≤ z ∧ z ≤ max x y
instance (z x y : ℕ) : Decidable (InR z x y) := inferInstanceAs (Decidable (_ ∧ _))
/-! ### The index view -/
end Lax689794Proofs.Seq
end
/-! ### `Lax689794Proofs.Seq.Stack` -/
section
/-!
# The stack algorithm computing the typical sequence
`typical a` is a left fold of `push` over `a`; the intermediate state is always a normal
form. `push t y` cuts the stack back to the *leftmost* index `i` whose entry `t_i` "sees"
the rest of the stack `t_{i+1}, …` inside the interval spanned by `t_i` and the new entry `y`,
and then appends `y`.
-/
namespace Lax689794Proofs.Seq
/-- The part of the stack that survives when `y` is pushed. -/
def cut : List ℕ → ℕ → List ℕ
| [], _ => []
| x :: t, y =>
if (∀ z ∈ t, InR z x y) then (if t = [] ∧ x = y then [] else [x]) else x :: cut t y
/-- Push `y` on the stack `t` (bottom first). -/
def push (t : List ℕ) (y : ℕ) : List ℕ := cut t y ++ [y]
/-- The typical sequence `τ(a)` (Def. 3.5), computed by the stack algorithm. -/
def typical (a : List ℕ) : List ℕ := a.foldl push []
/-! ### Entries of `t.take (i+1) ++ [y]` -/
/-! ### `push` preserves normal forms -/
/-! ### The fixed points of `push` -/
/-! ### Absorption: pushing an entry that the cut index of `y` already sees changes nothing -/
/-! ### Skipping a window -/
end Lax689794Proofs.Seq
end
end SourceModule3
-- Lax689794Proofs.Seq.Ext
section SourceModule5
/-!
# Extensions of integer sequences (Def. 3.6) and Lemma 3.6
`Ext a a'` says `a' ∈ E(a)`: `a'` arises from `a` by repeating every entry at least once.
It is defined by the "stay or move" recursion on `a'` (each entry of `a'` is either another copy
of the current entry of `a`, or the first copy of the next one), which is decidable
(`extB`), and equivalent to the paper's index description `1 = t₁ < … < t_{n+1}` (see
`ext_cons_iff`, the block form).
-/
namespace Lax689794Proofs.Seq
/-- Boolean version of `Ext`: recursion on the extension. -/
def extB : List ℕ → List ℕ → Bool
| [], [] => true
| [], _ :: _ => false
| _ :: _, [] => false
| x :: a, y :: w => (y == x) && (extB (x :: a) w || extB a w)
/-- `Ext a a'` : `a' ∈ E(a)` (Def. 3.6). -/
def Ext (a a' : List ℕ) : Prop := extB a a' = true
instance (a a' : List ℕ) : Decidable (Ext a a') := inferInstanceAs (Decidable (_ = true))
@[simp] theorem ext_nil_nil : Ext [] [] := rfl
@[simp] theorem ext_nil_cons (y : ℕ) (w : List ℕ) : ¬ Ext [] (y :: w) := by simp [Ext, extB]
@[simp] theorem ext_cons_nil (x : ℕ) (a : List ℕ) : ¬ Ext (x :: a) [] := by simp [Ext, extB]
theorem ext_cons_cons {x y : ℕ} {a w : List ℕ} :
Ext (x :: a) (y :: w) ↔ y = x ∧ (Ext (x :: a) w ∨ Ext a w) := by
simp [Ext, extB]
theorem ext_nil_iff {w : List ℕ} : Ext [] w ↔ w = [] := by
cases w with
| nil => simp
| cons y w => simp
theorem ext_nil_right {a : List ℕ} : Ext a [] ↔ a = [] := by
cases a with
| nil => simp
| cons x a => simp
/-- Block form: an extension of `x :: a` is `p+1` copies of `x` followed by an extension of `a`. -/
theorem ext_cons_iff {x : ℕ} {a w : List ℕ} :
Ext (x :: a) w ↔ ∃ p u, w = List.replicate (p + 1) x ++ u ∧ Ext a u := by
constructor
· induction w with
| nil => intro h; exact absurd h (ext_cons_nil x a)
| cons y w' ih =>
intro h
obtain ⟨rfl, h | h⟩ := ext_cons_cons.mp h
· obtain ⟨p, u, rfl, hu⟩ := ih h
exact ⟨p + 1, u, by simp [List.replicate_succ], hu⟩
· exact ⟨0, w', by simp, h⟩
· rintro ⟨p, u, rfl, hu⟩
induction p with
| zero => exact ext_cons_cons.mpr ⟨rfl, Or.inr hu⟩
| succ p ih =>
rw [List.replicate_succ, List.cons_append]
exact ext_cons_cons.mpr ⟨rfl, Or.inl ih⟩
theorem Ext.refl (a : List ℕ) : Ext a a := by
induction a with
| nil => exact ext_nil_nil
| cons x a ih => exact ext_cons_cons.mpr ⟨rfl, Or.inr ih⟩
theorem Ext.trans {a b c : List ℕ} (h1 : Ext a b) (h2 : Ext b c) : Ext a c := by
induction c generalizing a b with
| nil => rw [ext_nil_right] at h2 ⊢; subst h2; exact ext_nil_right.mp h1
| cons z c' ih =>
cases b with
| nil => exact absurd h2 (ext_nil_cons z c')
| cons y b' =>
obtain ⟨rfl, h2 | h2⟩ := ext_cons_cons.mp h2
· cases a with
| nil => exact absurd h1 (ext_nil_cons _ _)
| cons x a' =>
obtain ⟨rfl, _⟩ := ext_cons_cons.mp h1
exact ext_cons_cons.mpr ⟨rfl, Or.inl (ih h1 h2)⟩
· cases a with
| nil => exact absurd h1 (ext_nil_cons _ _)
| cons x a' =>
obtain ⟨rfl, h1' | h1'⟩ := ext_cons_cons.mp h1
· exact ext_cons_cons.mpr ⟨rfl, Or.inl (ih h1' h2)⟩
· exact ext_cons_cons.mpr ⟨rfl, Or.inr (ih h1' h2)⟩
/-- **Lemma 3.18** (concatenation of extensions). -/
theorem Ext.append {a b c d : List ℕ} (h1 : Ext a b) (h2 : Ext c d) : Ext (a ++ c) (b ++ d) := by
induction a generalizing b with
| nil => rw [ext_nil_iff] at h1; subst h1; exact h2
| cons x a ih =>
obtain ⟨p, u, rfl, hu⟩ := ext_cons_iff.mp h1
exact ext_cons_iff.mpr ⟨p, u ++ d, by simp [List.append_assoc], ih hu⟩
theorem ext_replicate {x p q : ℕ} (hp : 1 ≤ p) (hpq : p ≤ q) :
Ext (List.replicate p x) (List.replicate q x) := by
induction p generalizing q with
| zero => omega
| succ p ih =>
rw [List.replicate_succ]
obtain ⟨q', rfl⟩ : ∃ q', q = q' + 1 := ⟨q - 1, by omega⟩
rw [List.replicate_succ]
by_cases hp0 : p = 0
· subst hp0
simp only [List.replicate_zero]
exact ext_cons_iff.mpr ⟨q', [], by simp [List.replicate_succ], ext_nil_nil⟩
· exact ext_cons_iff.mpr ⟨0, List.replicate q' x, by simp, ih (by omega) (by omega)⟩
/-! ### Uniform stretching -/
/-- Repeat every entry `k` times. -/
def stretch (k : ℕ) (a : List ℕ) : List ℕ := a.flatMap (fun x => List.replicate k x)
@[simp] theorem stretch_nil (k : ℕ) : stretch k [] = [] := rfl
@[simp] theorem stretch_cons (k x : ℕ) (a : List ℕ) :
stretch k (x :: a) = List.replicate k x ++ stretch k a := by simp [stretch]
theorem stretch_append (k : ℕ) (a b : List ℕ) : stretch k (a ++ b) = stretch k a ++ stretch k b := by
simp [stretch]
theorem stretch_replicate (k n x : ℕ) : stretch k (List.replicate n x) = List.replicate (k * n) x := by
induction n with
| zero => rw [List.replicate_zero, stretch_nil]; simp
| succ n ih =>
rw [List.replicate_succ, stretch_cons, ih, ← List.replicate_add]
congr 1; ring
/-- Stretching a common base far enough gives an extension of any other extension of it. -/
theorem ext_stretch_of {a a' a₂ : List ℕ} {k : ℕ} (h1 : Ext a a') (h2 : Ext a a₂)
(hk : a₂.length ≤ k) : Ext a₂ (stretch k a') := by
induction a generalizing a' a₂ with
| nil =>
rw [ext_nil_iff] at h1 h2; subst h1; subst h2; exact ext_nil_nil
| cons x a ih =>
obtain ⟨q, u', rfl, hu'⟩ := ext_cons_iff.mp h1
obtain ⟨p, u₂, rfl, hu₂⟩ := ext_cons_iff.mp h2
simp only [List.length_append, List.length_replicate] at hk
rw [stretch_append, stretch_replicate]
exact Ext.append (ext_replicate (by omega) (by nlinarith)) (ih hu' hu₂ (by omega))
/-! ### Lifting along an extension -/
/-- If `w` extends `u` and `v` is related to `u` entrywise, then `v` has an extension related to
`w` entrywise (repeat the entries of `v` as those of `u` are repeated). -/
theorem ext_lift {R : ℕ → ℕ → Prop} {u w v : List ℕ} (h : Ext u w) (hR : List.Forall₂ R v u) :
∃ x, Ext v x ∧ List.Forall₂ R x w := by
induction w generalizing u v with
| nil =>
rw [ext_nil_right] at h; subst h
obtain rfl := List.forall₂_nil_right_iff.mp hR
exact ⟨[], ext_nil_nil, List.Forall₂.nil⟩
| cons y w ih =>
cases u with
| nil => exact absurd h (ext_nil_cons _ _)
| cons x0 u' =>
obtain ⟨rfl, h | h⟩ := ext_cons_cons.mp h
· obtain ⟨v0, v', hv0, hv', rfl⟩ := List.forall₂_cons_right_iff.mp hR
obtain ⟨x1, hx1, hx1R⟩ := ih h hR
exact ⟨v0 :: x1, ext_cons_cons.mpr ⟨rfl, Or.inl hx1⟩, List.Forall₂.cons hv0 hx1R⟩
· obtain ⟨v0, v', hv0, hv', rfl⟩ := List.forall₂_cons_right_iff.mp hR
obtain ⟨x1, hx1, hx1R⟩ := ih h hv'
exact ⟨v0 :: x1, ext_cons_cons.mpr ⟨rfl, Or.inr hx1⟩, List.Forall₂.cons hv0 hx1R⟩
end Lax689794Proofs.Seq
end SourceModule5
-- Lax689794Proofs.Seq.Dom
section SourceModule6
/-! ### `Lax689794Proofs.Seq.Rel` -/
section
/-!
# Entrywise order on sequences
`List.Forall₂ (· ≤ ·) a b` is "`a ≤ b`" of the paper (same length, `a_i ≤ b_i`). Small helper
lemmas about it.
-/
namespace Lax689794Proofs.Seq
/-- `a ≤ b` for sequences of the same length (Section 3 preliminaries). -/
abbrev LeSeq (a b : List ℕ) : Prop := List.Forall₂ (· ≤ ·) a b
theorem LeSeq.refl (a : List ℕ) : LeSeq a a := by
induction a with
| nil => exact List.Forall₂.nil
| cons x a ih => exact List.Forall₂.cons (Nat.le_refl x) ih
theorem LeSeq.trans {a b c : List ℕ} (h1 : LeSeq a b) (h2 : LeSeq b c) : LeSeq a c := by
induction h1 generalizing c with
| nil => cases h2; exact List.Forall₂.nil
| cons hab _ ih =>
cases h2 with
| cons hbc h2' => exact List.Forall₂.cons (Nat.le_trans hab hbc) (ih h2')
theorem LeSeq.length_eq {a b : List ℕ} (h : LeSeq a b) : a.length = b.length :=
List.Forall₂.length_eq h
theorem LeSeq.flip {a b : List ℕ} (h : List.Forall₂ (fun p q => q ≤ p) a b) : LeSeq b a := by
induction h with
| nil => exact List.Forall₂.nil
| cons hab _ ih => exact List.Forall₂.cons hab ih
theorem LeSeq.flip' {a b : List ℕ} (h : LeSeq a b) : List.Forall₂ (fun p q => q ≤ p) b a := by
induction h with
| nil => exact List.Forall₂.nil
| cons hab _ ih => exact List.Forall₂.cons hab ih
end Lax689794Proofs.Seq
end
/-! ### `Lax689794Proofs.Seq.Dom` -/
section
/-!
# The dominance preorder `≺` (Defs 3.7; Lemmas 3.7, 3.9, 3.10; Cor. 3.8, 3.11)
`Dom a b` is `a ≺ b`: there are extensions `a* ∈ E(a)`, `b* ∈ E(b)` of the same length with
`a* ≤ b*`. `DomEquiv a b` is `a ≡ b`.
-/
namespace Lax689794Proofs.Seq
/-- `a ≺ b` (Def. 3.7). -/
def Dom (a b : List ℕ) : Prop :=
∃ a' b', Ext a a' ∧ Ext b b' ∧ LeSeq a' b'
/-- `a ≡ b` (Def. 3.7): `a ≺ b` and `b ≺ a`. -/
def DomEquiv (a b : List ℕ) : Prop := Dom a b ∧ Dom b a
theorem Dom.refl (a : List ℕ) : Dom a a := ⟨a, a, Ext.refl a, Ext.refl a, LeSeq.refl a⟩
/-- **Lemma 3.7**: `≺` is transitive. -/
theorem Dom.trans {a b c : List ℕ} (h1 : Dom a b) (h2 : Dom b c) : Dom a c := by
obtain ⟨a1, b1, ha1, hb1, hab⟩ := h1
obtain ⟨b2, c2, hb2, hc2, hbc⟩ := h2
set k := b1.length + b2.length with hk
have e1 : Ext b1 (stretch k b) := ext_stretch_of (Ext.refl b) hb1 (by omega)
have e2 : Ext b2 (stretch k b) := ext_stretch_of (Ext.refl b) hb2 (by omega)
obtain ⟨x, hx, hxw⟩ := ext_lift e1 hab
obtain ⟨y, hy, hyw⟩ := ext_lift e2 (R := fun p q => q ≤ p) hbc.flip'
exact ⟨x, y, ha1.trans hx, hc2.trans hy, LeSeq.trans hxw (LeSeq.flip hyw)⟩
/-- Preorder instance, for `calc`/`gcongr`-style use. -/
instance : Trans Dom Dom Dom := ⟨Dom.trans⟩
/-! ### Lemma 3.9 / 3.10 -/
/-! ### `≺` is decidable: the alignment recursion
`domB (x :: a) (y :: b)` walks a monotone lattice path: the current entries must satisfy
`x ≤ y`, and then either both sequences end, or one of them advances, or both do. -/
/-- Decision procedure for `a ≺ b` (lattice-path recursion). -/
def domB : List ℕ → List ℕ → Bool
| [], [] => true
| [], _ :: _ => false
| _ :: _, [] => false
| x :: a, y :: b =>
decide (x ≤ y) &&
((a.isEmpty && b.isEmpty) || domB a (y :: b) || domB (x :: a) b || domB a b)
termination_by l1 l2 => l1.length + l2.length
theorem domB_cons_cons (x y : ℕ) (a b : List ℕ) :
domB (x :: a) (y :: b) = (decide (x ≤ y) &&
((a.isEmpty && b.isEmpty) || domB a (y :: b) || domB (x :: a) b || domB a b)) := by
rw [domB]
theorem domB_of_dom_aux : ∀ (a1 : List ℕ) (a b b1 : List ℕ),
Ext a a1 → Ext b b1 → LeSeq a1 b1 → domB a b = true := by
intro a1
induction a1 with
| nil =>
intro a b b1 h1 h2 h3
rw [ext_nil_right] at h1; subst h1
have := LeSeq.length_eq h3
have hb1 : b1 = [] := List.length_eq_zero_iff.mp (by simpa using this.symm)
subst hb1
rw [ext_nil_right] at h2; subst h2
simp [domB]
| cons x1 a1 ih =>
intro a b b1 h1 h2 h3
cases h3 with
| cons hxy h3' =>
rename_i y1 b1'
cases a with
| nil => exact absurd h1 (ext_nil_cons _ _)
| cons x a0 =>
cases b with
| nil => exact absurd h2 (ext_nil_cons _ _)
| cons y b0 =>
obtain ⟨rfl, h1' | h1'⟩ := ext_cons_cons.mp h1 <;>
obtain ⟨rfl, h2' | h2'⟩ := ext_cons_cons.mp h2
· exact ih _ _ _ h1' h2' h3'
· have := ih _ _ _ h1' h2' h3'
rw [domB_cons_cons]; simp [hxy, this]
· have := ih _ _ _ h1' h2' h3'
rw [domB_cons_cons]; simp [hxy, this]
· have := ih _ _ _ h1' h2' h3'
rw [domB_cons_cons]; simp [hxy, this]
theorem dom_of_domB_aux : ∀ (n : ℕ) (a b : List ℕ), a.length + b.length = n →
domB a b = true → Dom a b := by
intro n
induction n using Nat.strong_induction_on with
| _ n ih =>
intro a b hn h
cases a with
| nil =>
cases b with
| nil => exact Dom.refl []
| cons y b => simp [domB] at h
| cons x a =>
cases b with
| nil => simp [domB] at h
| cons y b =>
rw [domB_cons_cons] at h
simp only [Bool.and_eq_true, decide_eq_true_eq, Bool.or_eq_true] at h
obtain ⟨hxy, h⟩ := h
simp only [List.length_cons] at hn
rcases h with ((h | h) | h) | h
· simp only [Bool.and_eq_true, List.isEmpty_iff] at h
obtain ⟨rfl, rfl⟩ := h
exact ⟨[x], [y], Ext.refl _, Ext.refl _, List.Forall₂.cons hxy List.Forall₂.nil⟩
· obtain ⟨a1, b1, ha1, hb1, hle⟩ := ih (a.length + (y :: b).length) (by simp at *; omega) a
(y :: b) rfl h
refine ⟨x :: a1, y :: b1, ext_cons_cons.mpr ⟨rfl, Or.inr ha1⟩,
ext_cons_cons.mpr ⟨rfl, Or.inl hb1⟩, List.Forall₂.cons hxy hle⟩
· obtain ⟨a1, b1, ha1, hb1, hle⟩ := ih ((x :: a).length + b.length) (by simp at *; omega)
(x :: a) b rfl h
refine ⟨x :: a1, y :: b1, ext_cons_cons.mpr ⟨rfl, Or.inl ha1⟩,
ext_cons_cons.mpr ⟨rfl, Or.inr hb1⟩, List.Forall₂.cons hxy hle⟩
· obtain ⟨a1, b1, ha1, hb1, hle⟩ := ih (a.length + b.length) (by omega) a b rfl h
refine ⟨x :: a1, y :: b1, ext_cons_cons.mpr ⟨rfl, Or.inr ha1⟩,
ext_cons_cons.mpr ⟨rfl, Or.inr hb1⟩, List.Forall₂.cons hxy hle⟩
/-- `a ≺ b` is decided by the lattice-path recursion `domB`. -/
theorem dom_iff_domB {a b : List ℕ} : Dom a b ↔ domB a b = true :=
⟨fun ⟨a1, b1, h1, h2, h3⟩ => domB_of_dom_aux a1 a b b1 h1 h2 h3,
dom_of_domB_aux _ a b rfl⟩
instance : DecidableRel Dom := fun a b => decidable_of_iff _ dom_iff_domB.symm
instance : DecidableRel DomEquiv := fun a b => inferInstanceAs (Decidable (Dom a b ∧ Dom b a))
end Lax689794Proofs.Seq
end
end SourceModule6
-- Lax689794Proofs.Chars.Defs
section SourceModule7
namespace Lax689794Proofs.Chars
open Lax689794Proofs.Seq Lax689794Proofs.Trees
/-! ## the characteristic trees -/
/-- A characteristic (a rooted tree of runs). -/
inductive CT where
| node (S : Finset ℕ) (y : List ℕ) (kids : List CT)
mutual
/-- Decidable equality (the `deriving` handler does not support this nested inductive). -/
def decEqCT : (a b : CT) → Decidable (a = b)
| .node S y ks, .node S' y' ks' =>
match decEq S S' with
| isFalse h => isFalse (fun e => h (by cases e; rfl))
| isTrue h₁ =>
match decEq y y' with
| isFalse h => isFalse (fun e => h (by cases e; rfl))
| isTrue h₂ =>
match decEqCTL ks ks' with
| isFalse h => isFalse (fun e => h (by cases e; rfl))
| isTrue h₃ => isTrue (by subst h₁ h₂ h₃; rfl)
def decEqCTL : (a b : List CT) → Decidable (a = b)
| [], [] => isTrue rfl
| [], _ :: _ => isFalse (by intro h; cases h)
| _ :: _, [] => isFalse (by intro h; cases h)
| k :: ks, k' :: ks' =>
match decEqCT k k' with
| isFalse h => isFalse (fun e => h (by cases e; rfl))
| isTrue h₁ =>
match decEqCTL ks ks' with
| isFalse h => isFalse (fun e => h (by cases e; rfl))
| isTrue h₂ => isTrue (by subst h₁ h₂; rfl)
end
instance : DecidableEq CT := decEqCT
namespace CT
def S : CT → Finset ℕ | node S _ _ => S
def y : CT → List ℕ | node _ y _ => y
def kids : CT → List CT | node _ _ ks => ks
mutual
/-- All boundary vertices occurring in the labels of the runs. -/
def verts : CT → Finset ℕ
| node S _ ks => S ∪ vertsL ks
def vertsL : List CT → Finset ℕ
| [] => ∅
| k :: ks => verts k ∪ vertsL ks
end
mutual
/-- The largest entry of any run sequence. -/
def maxEntry : CT → ℕ
| node _ y ks => max (y.foldr max 0) (maxEntryL ks)
def maxEntryL : List CT → ℕ
| [] => 0
| k :: ks => max (maxEntry k) (maxEntryL ks)
end
mutual
/-- Apply `f` to every label. -/
def relabel (f : Finset ℕ → Finset ℕ) : CT → CT
| node S y ks => node (f S) y (relabelL f ks)
def relabelL (f : Finset ℕ → Finset ℕ) : List CT → List CT
| [] => []
| k :: ks => relabel f k :: relabelL f ks
end
def isLeaf (t : CT) : Bool := t.kids.isEmpty
/-- The least vertex owned by a kid (present in its subtree, absent from the parent label). -/
def key (S : Finset ℕ) (k : CT) : WithTop ℕ := (k.verts \ S).min
/-- Sort kids by `key` (stable). -/
def sortKids (S : Finset ℕ) (ks : List CT) : List CT :=
ks.mergeSort (fun a b => decide (key S a ≤ key S b))
/-- One step of the normal form, given the already normalised kids. -/
def normNode (S : Finset ℕ) (y : List ℕ) (ks : List CT) : CT :=
match ks.filter (fun k => !(k.isLeaf && decide (k.S ⊆ S))) with
| [] => node S (y.take 1) []
| [k] => if k.S = S then node S (typical (y ++ k.y)) k.kids else node S y [k]
| ks' => node S y (sortKids S ks')
mutual
/-- The normal form (i)–(iii). -/
def norm : CT → CT
| node S y ks => normNode S y (normL ks)
def normL : List CT → List CT
| [] => []
| k :: ks => norm k :: normL ks
end
/-- The initial characteristic (leaf of a nice decomposition, empty boundary). -/
def start : CT := node ∅ [0] []
/-- **Forget** `x`. -/
def forgetC (x : ℕ) (t : CT) : CT := norm (relabel (fun S => S.erase x) t)
/-! ### join -/
/-- A state of the lattice dynamic programme: the `τ` of the sums along a path, and (reversed) that path. -/
abbrev LState := List ℕ × List (ℕ × ℕ)
/-- Keep the first state for every `τ`-prefix. -/
def dedupKey (l : List LState) : List LState :=
l.foldl (fun acc s => if acc.any (fun t => decide (t.1 = s.1)) then acc else acc ++ [s]) []
/-- The states of cell `(i, j)` (whose entry is `z = a_i + b_j`) from those of the three predecessors. -/
def cellOf (i j z : ℕ) (up left diag : List LState) : List LState :=
dedupKey ((up ++ left ++ diag).map (fun s => (push s.1 z, (i, j) :: s.2)))
/-- One row `i` of the lattice (`x = a_i`): `ups` the row above, `diag` the state list of the up-left neighbour,
`left` that of the left neighbour. -/
def rowCells (i x : ℕ) : List ℕ → ℕ → List (List LState) → List LState → List LState → List (List LState)
| [], _, _, _, _ => []
| y :: b, j, ups, diag, left =>
let c := cellOf i j (x + y) (ups.headD []) left diag
c :: rowCells i x b (j + 1) ups.tail (ups.headD []) c
/-- Process the rows `a_i, a_{i+1}, …` (`prev` the row above); returns the last row. The first row starts from the
seed state `([], [])` at cell `(0,0)`. -/
def latticeRows (b : List ℕ) : ℕ → List ℕ → List (List LState) → List (List LState)
| _, [], prev => prev
| i, x :: a, prev =>
latticeRows b (i + 1) a (rowCells i x b 0 prev (if i = 0 then [([], [])] else []) [])
/-- The states of the final cell `(|a|-1, |b|-1)`: one state per typical ring sum `τ c`, `c ∈ a ⊕ b`, with the
first lattice path (reversed) that reaches it. (`reference/typical.py: ring`, `real.py: find_path`.) -/
def latticeStates (a b : List ℕ) : List LState :=
match a, b with
| [], _ => []
| _, [] => []
| _, _ => (latticeRows b 0 a []).getLast?.getD []
/-- The typical ring sums as a computable list (dynamic programme over the lattice of pairs, with `τ` of the prefix
as state; `reference/typical.py: ring`). -/
def ringTypList (a b : List ℕ) : List (List ℕ) := (latticeStates a b).map Prod.fst
mutual
/-- **Join.** All characteristics of joins of decompositions with characteristics `t₁`, `t₂` (same shape). The
sizes of the two sides add, the restricted bag being counted once; entries above `kmax` are discarded. -/
def joinC (kmax : ℕ) : CT → CT → List CT
| node S y ks, node S' y' ks' =>
if S = S' ∧ ks.length = ks'.length then
let ys := (((ringTypList y y').map (fun d => d.map (· - S.card))).dedup).filter (fun d => d.all (· ≤ kmax))
(joinKids kmax ks ks').flatMap (fun kk => ys.map (fun d => node S d kk))
else []
def joinKids (kmax : ℕ) : List CT → List CT → List (List CT)
| k :: ks, k' :: ks' => (joinC kmax k k').flatMap (fun c => (joinKids kmax ks ks').map (c :: ·))
| [], [] => [[]]
| _, _ => []
end
/-! ### introduce -/
def plus1 (y : List ℕ) : List ℕ := y.map (· + 1)
set_option genSizeOfSpec false in
/-- A cut of a typical sequence: first type at `f` (the entry `y_f` is duplicated), second type after `f`. -/
inductive Cut where
| t1 (f : ℕ)
| t2 (f : ℕ)
deriving DecidableEq
def Cut.isT1 : Cut → Bool
| .t1 _ => true
| .t2 _ => false
set_option genInjectivity false in
set_option genSizeOfSpec false in
/-- How the new vertex's region `W` sits in a run whose first tree node is in `W`: it ends inside the run, or it
covers the whole run and continues (or not) into each kid run. -/
inductive WPlan where
| endAt (c : Cut)
| whole (kids : List (Option WPlan))
set_option genInjectivity false in
set_option genSizeOfSpec false in
/-- An option for the introduction of a vertex: a new leaf branch hanging at a tree node of a run (case (b)), or a
region `W` meeting the core with its topmost tree node inside a run (case (a)). -/
inductive Plan where
| att (c : Option Cut) (chain : List (Finset ℕ)) (M : Finset ℕ)
| top (pre : Option Cut) (w : WPlan)
mutual
/-- Case (a): `W` contains the first tree node of the run, entered at typical index `lo`.
Returns (plan, replacement subtree, vertices of `B` covered by `W`). -/
def winPlans (v : ℕ) (lo : ℕ) : CT → List (WPlan × CT × Finset ℕ)
| node S y ks =>
let S1 := insert v S
let s := y.length
let ends1 := (List.range' lo (s - lo)).map fun f =>
(WPlan.endAt (Cut.t1 f), node S1 (plus1 ((y.take (f + 1)).drop lo)) [node S (y.drop f) ks], S)
let ends2 := (List.range' lo (s - 1 - lo)).map fun f =>
(WPlan.endAt (Cut.t2 f), node S1 (plus1 ((y.take (f + 1)).drop lo)) [node S (y.drop (f + 1)) ks], S)
let whole := (kidChoices v ks).map fun combo =>
(WPlan.whole (combo.map (·.1)), node S1 (plus1 (y.drop lo)) (combo.map (·.2.1)),
combo.foldl (fun a c => a ∪ c.2.2) S)
ends1 ++ ends2 ++ whole
/-- Per kid: leave it (`none`, covering nothing) or let `W` continue into it. -/
def kidChoices (v : ℕ) : List CT → List (List (Option WPlan × CT × Finset ℕ))
| [] => [[]]
| k :: ks =>
let opts : List (Option WPlan × CT × Finset ℕ) :=
(none, k, ∅) :: (winPlans v 0 k).map (fun p => (some p.1, p.2.1, p.2.2))
opts.flatMap fun o => (kidChoices v ks).map (o :: ·)
end
/-- Case (a) with an optional pre-cut: `W`'s topmost tree node lies inside the run. -/
def wtopPlans (v : ℕ) : CT → List (Plan × CT × Finset ℕ)
| t@(node S y _) =>
let s := y.length
let direct := (winPlans v 0 t).map fun p => (Plan.top none p.1, p.2.1, p.2.2)
let pre1 := (List.range s).flatMap fun f =>
(winPlans v f t).map fun p => (Plan.top (some (Cut.t1 f)) p.1, node S (y.take (f + 1)) [p.2.1], p.2.2)
let pre2 := (List.range (s - 1)).flatMap fun f =>
(winPlans v (f + 1) t).map fun p => (Plan.top (some (Cut.t2 f)) p.1, node S (y.take (f + 1)) [p.2.1], p.2.2)
direct ++ pre1 ++ pre2
/-- The candidate leaf labels / chain elements for a branch hanging at a run with label `S` (needs `N ⊆ S`):
`N ∪ c` for every subset `c` of `S \ N`. -/
def chainCands (S N : Finset ℕ) : List (Finset ℕ) :=
(((S \ N).sort (· ≤ ·)).sublists).map (fun c => N ∪ c.toFinset)
/-- The enumeration of chains, with fuel: at each level output the leaf labels `M ⊆ bound`, and extend the chain by a
candidate `X ⊆ bound` (strictly below `bound` once the chain is non-empty). -/
def chainsGo (cands : List (Finset ℕ)) :
ℕ → Finset ℕ → List (Finset ℕ) → List (List (Finset ℕ) × Finset ℕ)
| 0, bound, chain => (cands.filter (· ⊆ bound)).map (fun M => (chain, M))
| fuel + 1, bound, chain =>
(cands.filter (· ⊆ bound)).map (fun M => (chain, M)) ++
(cands.filter (fun X => decide (X ⊆ bound) && (chain.isEmpty || decide (X ⊂ bound)))).flatMap
(fun X => chainsGo cands fuel X (chain ++ [X]))
/-- The shapes of a new branch hanging at a run with label `S` (needs `N ⊆ S`): a strictly decreasing chain of
subsets of `S` containing `N`, then a leaf labelled `M ∪ {v}`, `N ⊆ M` below the last chain element.
(`reference/chars.py: all_chains`; *all* nested chains are needed — this corrects a tempting simplification.)
The fuel `|S| + 1` bounds the chain length. -/
def allChains (S N : Finset ℕ) : List (List (Finset ℕ) × Finset ℕ) :=
chainsGo (chainCands S N) (S.card + 1) S []
/-- The branch subtree: the chain of nested labels ending in the leaf `M ∪ {v}`. -/
def pathSubtree (v : ℕ) (chain : List (Finset ℕ)) (M : Finset ℕ) : CT :=
chain.foldr (fun X acc => node X [X.card] [acc]) (node (insert v M) [M.card + 1] [])
/-- Case (b): hang a new branch at (a tree node of) the run `node S y ks`; with an optional cut of the run first. -/
def attachPlans (v : ℕ) (N : Finset ℕ) : CT → List (Plan × CT)
| node S y ks =>
(allChains S N).flatMap fun cm =>
let br := pathSubtree v cm.1 cm.2
(Plan.att none cm.1 cm.2, node S y (ks ++ [br])) ::
((List.range y.length).map fun f =>
(Plan.att (some (Cut.t1 f)) cm.1 cm.2, node S (y.take (f + 1)) [br, node S (y.drop f) ks])) ++
((List.range (y.length - 1)).map fun f =>
(Plan.att (some (Cut.t2 f)) cm.1 cm.2, node S (y.take (f + 1)) [br, node S (y.drop (f + 1)) ks]))
mutual
/-- All options (path to the run, plan, un-normalised result) for introducing `v` with neighbours `N`. -/
def introPlans (v : ℕ) (N : Finset ℕ) : CT → List (List ℕ × Plan × CT)
| t@(node S y ks) =>
((wtopPlans v t).filter (fun p => decide (N ⊆ p.2.2))).map (fun p => ([], p.1, p.2.1)) ++
(if N ⊆ S then (attachPlans v N t).map (fun p => ([], p.1, p.2)) else []) ++
introKids v N S y [] ks
def introKids (v : ℕ) (N S : Finset ℕ) (y : List ℕ) (pre : List CT) : List CT → List (List ℕ × Plan × CT)
| [] => []
| k :: post =>
(introPlans v N k).map (fun r => (pre.length :: r.1, r.2.1, node S y (pre ++ r.2.2 :: post))) ++
introKids v N S y (pre ++ [k]) post
end
/-- **Introduce** `v` (with neighbours `N` in the boundary): the normalised results of all options. -/
def introC (kmax : ℕ) (v : ℕ) (N : Finset ℕ) (t : CT) : List CT :=
((introPlans v N t).map (fun r => norm r.2.2)).filter (fun c => decide (c.maxEntry ≤ kmax))
/-! ### dominance -/
mutual
/-- `DomC a b`: same shape, run-wise `Dom` ("`a` is at least as good as `b`"). -/
def DomC : CT → CT → Prop
| node S y ks, node S' y' ks' => S = S' ∧ Dom y y' ∧ DomCL ks ks'
def DomCL : List CT → List CT → Prop
| [], [] => True
| k :: ks, k' :: ks' => DomC k k' ∧ DomCL ks ks'
| _, _ => False
end
mutual
def domCB : CT → CT → Bool
| node S y ks, node S' y' ks' => decide (S = S') && domB y y' && domCBL ks ks'
def domCBL : List CT → List CT → Bool
| [], [] => true
| k :: ks, k' :: ks' => domCB k k' && domCBL ks ks'
| _, _ => false
end
/-! ### well-formed characteristics -/
mutual
/-- Local shape invariants of a run (label inside `B`, typical sequence at least `|S|`, a leaf run has one entry, no
prunable leaf kid, a single kid has a different label, kids strictly ordered by `key`), recursively. -/
def Good (B : Finset ℕ) : CT → Prop
| node S y ks =>
S ⊆ B ∧ typical y = y ∧ y ≠ [] ∧ (∀ e ∈ y, S.card ≤ e) ∧ (ks = [] → y.length = 1) ∧
(∀ k ∈ ks, k.kids = [] → ¬ k.S ⊆ S) ∧ (∀ k, ks = [k] → k.S ≠ S) ∧
ks.Pairwise (fun a b => key S a < key S b) ∧ GoodL B ks
def GoodL (B : Finset ℕ) : List CT → Prop
| [] => True
| k :: ks => Good B k ∧ GoodL B ks
end
mutual
/-- Occurrences of every vertex form a connected subtree of runs (as `RT.Conn`). -/
def Conn : CT → Prop
| node S _ ks => ConnL ks ∧ (∀ k ∈ ks, ∀ v ∈ S, v ∈ verts k → v ∈ k.S) ∧
ks.Pairwise (fun k₁ k₂ => ∀ v, v ∈ verts k₁ → v ∈ verts k₂ → v ∈ S)
def ConnL : List CT → Prop
| [] => True
| k :: ks => Conn k ∧ ConnL ks
end
/-- Well-formed characteristics over the boundary `B` with sizes `≤ kmax`: every boundary vertex occurs
(`verts = B`), local invariants, connectedness. -/
structure Wf (B : Finset ℕ) (kmax : ℕ) (t : CT) : Prop where
verts_eq : t.verts = B
good : Good B t
conn : Conn t
bounded : t.maxEntry ≤ kmax
end CT
end Lax689794Proofs.Chars
/-! ## the characteristic of a real rooted decomposition -/
namespace Lax689794Proofs.Trees.RT
open Lax689794Proofs.Chars
mutual
/-- The un-normalised profile of a rooted tree relative to the boundary `B`: label `bag ∩ B`, size `|bag|`. -/
def prof (B : Finset ℕ) : RT → CT
| .node X ks => .node (X ∩ B) [X.card] (profL B ks)
def profL (B : Finset ℕ) : List RT → List CT
| [] => []
| k :: ks => prof B k :: profL B ks
end
/-- **The characteristic of a rooted partial decomposition** relative to `B`. -/
def char (B : Finset ℕ) (t : RT) : CT := CT.norm (t.prof B)
end Lax689794Proofs.Trees.RT
end SourceModule7
-- Lax689794Proofs.Chars.Alg
section SourceModule8
namespace Lax689794Proofs.Trees.NT
/-- The vertices below a node (`V⁺` of the paper). -/
def under : NT → Finset ℕ
| leaf => ∅
| intro v c => insert v c.under
| forget _ c => c.under
| join a b => a.under ∪ b.under
end Lax689794Proofs.Trees.NT
namespace Lax689794Proofs.Chars
open Lax689794Proofs.Seq Lax689794Proofs.Trees CT
/-! ## graphs, partial decompositions -/
/-- A graph as a Boolean adjacency function (computable); `Adj.graph` is the `SimpleGraph` it denotes. -/
abbrev Adj := ℕ → ℕ → Bool
def Adj.graph (adj : Adj) : SimpleGraph ℕ := SimpleGraph.fromRel (fun u v => adj u v = true)
end Lax689794Proofs.Chars
namespace Lax689794Proofs.Trees.NT
open Lax689794Proofs.Chars
/-- The "nice" side conditions that make the tables meaningful for the graph `adj`: shapes; *closedness* (a vertex is
introduced with all its neighbours below already in the bag: forgotten vertices have no neighbours outside);
*separation* (the two sides of a join meet only in the bag, and no edge joins the two sides outside the bag:
the last conjunct of `join`, added because without it the tables are unsound — a graph with an edge between the
two sides of a join satisfies all the other clauses). Both follow from being a tree decomposition
(`good_of_isNiceTD`). -/
def Good (adj : Adj) : NT → Prop
| leaf => True
| intro v c => v ∉ c.bag ∧ (∀ u ∈ c.under, adj v u = true → u ∈ c.bag) ∧ v ∉ c.under ∧ Good adj c
| forget v c => v ∈ c.bag ∧ Good adj c
| join a b => a.bag = b.bag ∧ a.under ∩ b.under ⊆ a.bag ∧ Good adj a ∧ Good adj b ∧
(∀ u ∈ a.under, ∀ v ∈ b.under, (adj u v = true ∨ adj v u = true) → u ∈ a.bag ∨ v ∈ a.bag)
end Lax689794Proofs.Trees.NT
namespace Lax689794Proofs.Chars
open Lax689794Proofs.Seq Lax689794Proofs.Trees CT
/-- A partial decomposition at a nice node: a tree decomposition of `G[V⁺]` of width `≤ k`. -/
def PTD (adj : Adj) (nt : NT) (k : ℕ) (t : RT) : Prop := t.IsTD adj.graph nt.under ∧ t.Width k
/-! ## phase A: the tables -/
/-- Neighbours of `v` in the boundary. -/
def nbrs (adj : Adj) (v : ℕ) (B : Finset ℕ) : Finset ℕ := B.filter (fun w => adj v w = true)
/-- Forget step on a table. -/
def forgetTable (x : ℕ) (T : List CT) : List CT := (T.map (CT.forgetC x)).dedup
/-- Introduce step on a table. -/
def introTable (kmax v : ℕ) (N : Finset ℕ) (T : List CT) : List CT := (T.flatMap (CT.introC kmax v N)).dedup
/-- Join step on two tables. -/
def joinTable (kmax : ℕ) (Ta Tb : List CT) : List CT :=
(Ta.flatMap fun ca => Tb.flatMap fun cb => CT.joinC kmax ca cb).dedup
/-- **The tables.** `k` is the target width; sizes are bounded by `k + 1`. There is no dominance pruning. -/
def tables (adj : Adj) (k : ℕ) : NT → List CT
| .leaf => [CT.start]
| .intro v c => introTable (k + 1) v (nbrs adj v c.bag) (tables adj k c)
| .forget x c => forgetTable x (tables adj k c)
| .join a b => joinTable (k + 1) (tables adj k a) (tables adj k b)
/-! ## phase B: analysis of a real tree -/
set_option genInjectivity false in
set_option genSizeOfSpec false in
/-- A node of a chain of a run: its bag and the junk subtrees hanging at it (children outside the core). -/
structure CNode where
bag : Finset ℕ
junk : List RT
set_option genInjectivity false in
set_option genSizeOfSpec false in
/-- The analysis of a real tree relative to a boundary: a run tree whose runs carry their chains of tree nodes. -/
inductive AR where
| run (S : Finset ℕ) (chain : List CNode) (kids : List AR)
namespace AR
def S : AR → Finset ℕ | run S _ _ => S
def chain : AR → List CNode | run _ c _ => c
def kids : AR → List AR | run _ _ ks => ks
def isLeaf (r : AR) : Bool := r.kids.isEmpty
mutual
/-- The characteristic read off the analysis (`analyze_char`: it is `RT.char`). -/
def char : AR → CT
| run S c ks => CT.node S (typical (c.map (fun n => n.bag.card))) (charL ks)
def charL : List AR → List CT
| [] => []
| k :: ks => char k :: charL ks
end
/-- A chain with the runs below its last node, reassembled as a real tree (junk first, the core successor last). -/
def chainToRT : List CNode → List RT → RT
| [], ks => .node ∅ ks
| [n], ks => .node n.bag (n.junk ++ ks)
| n :: m :: r, ks => .node n.bag (n.junk ++ [chainToRT (m :: r) ks])
mutual
/-- Reassemble the real tree. -/
def toRT : AR → RT
| run _ c ks => chainToRT c (toRTL ks)
def toRTL : List AR → List RT
| [] => []
| k :: ks => toRT k :: toRTL ks
end
end AR
/-- Sort the kids of a run with label `S` by the key of their characteristic (as `CT.sortKids`). -/
def sortAR (S : Finset ℕ) (ks : List AR) : List AR :=
ks.mergeSort (fun a b => decide (CT.key S a.char ≤ CT.key S b.char))
/-- One step of the analysis (the normal form of `CT.norm` on annotated trees), given the analysed kids together with
the real subtrees they came from (a pruned kid becomes junk of the node). -/
def analyzeNode (B X : Finset ℕ) (kids : List (RT × AR)) : AR :=
let S := X ∩ B
let pruned := fun (p : RT × AR) => p.2.isLeaf && decide (p.2.S ⊆ S)
let junk := (kids.filter pruned).map Prod.fst
let core := (kids.filter (fun p => !pruned p)).map Prod.snd
match core with
| [] => .run S [⟨X, junk⟩] []
| [k] => if k.S = S then .run S (⟨X, junk⟩ :: k.chain) k.kids else .run S [⟨X, junk⟩] [k]
| ks => .run S [⟨X, junk⟩] (sortAR S ks)
mutual
/-- **The analysis of a real tree** relative to the boundary `B` (Python `analyze`). -/
def analyze (B : Finset ℕ) : RT → AR
| .node X ks => analyzeNode B X (analyzeL B ks)
def analyzeL (B : Finset ℕ) : List RT → List (RT × AR)
| [] => []
| k :: ks => (k, analyze B k) :: analyzeL B ks
end
/-! ## phase B: surgery on the analysis -/
/-- Witness positions: the indices in the exact sequence of the entries of its typical sequence (a stack of
`(value, index)` pairs mirroring `Seq.push`; a repeated top value keeps its first index). -/
def wpush : List (ℕ × ℕ) → ℕ → ℕ → List (ℕ × ℕ)
| [], y, j => [(y, j)]
| (x, i) :: t, y, j =>
if t.all (fun z => decide (InR z.1 x y)) then
(if t.isEmpty && decide (x = y) then [(x, i)] else [(x, i), (y, j)])
else (x, i) :: wpush t y j
def witnessesAux : ℕ → List (ℕ × ℕ) → List ℕ → List (ℕ × ℕ)
| _, st, [] => st
| j, st, y :: a => witnessesAux (j + 1) (wpush st y j) a
/-- `witnesses a`: indices `w₁ < … < w_s` into `a` of the entries of `typical a`. -/
def witnesses (a : List ℕ) : List ℕ := (witnessesAux 0 [] a).map Prod.snd
/-- Duplicate the chain node `i` (the copy has the same bag, no junk, and takes over the successor). -/
def dupAfter (i : ℕ) (ns : List CNode) : List CNode :=
match ns[i]? with
| none => ns
| some n => ns.take (i + 1) ++ [⟨n.bag, []⟩] ++ ns.drop (i + 1)
/-- Cut the chain `ns` (with typical sequence `y` and witnesses `w`) at `c`: returns the new chain and the index
`c'` such that the left piece is `ns'[0..c']`; a first-type cut duplicates the witness node. -/
def cutAt (y w : List ℕ) : Cut → List CNode → List CNode × ℕ
| .t1 f, ns => (dupAfter (w.getD f 0) ns, w.getD f 0)
| .t2 f, ns =>
(ns, if y.getD f 0 < y.getD (f + 1) 0 then w.getD f 0 else w.getD (f + 1) 0 - 1)
/-- Add `v` to the bags of the chain nodes with index in `[s, e]` (`e = none`: to the end). -/
def addV (v s : ℕ) (e : Option ℕ) (ns : List CNode) : List CNode :=
ns.mapIdx fun i n => if decide (s ≤ i) && e.elim true (fun e => decide (i ≤ e)) then ⟨insert v n.bag, n.junk⟩ else n
/-- Hang a subtree at the chain node `x` (as junk). -/
def addJunk (x : ℕ) (br : RT) (ns : List CNode) : List CNode :=
ns.mapIdx fun i n => if i = x then ⟨n.bag, n.junk ++ [br]⟩ else n
/-- The new branch of a case-(b) plan as a real tree: the nested chain, then the leaf `M ∪ {v}`. -/
def branchRT (v : ℕ) (chain : List (Finset ℕ)) (M : Finset ℕ) : RT :=
chain.foldr (fun X acc => RT.node X [acc]) (RT.node (insert v M) [])
mutual
/-- Apply a region plan to a run (`process` of `real.py`): the region contains the first node of the run after the
optional pre-cut `pre`; `w` says where it ends / into which kids it continues. -/
def processRun (v : ℕ) (pre : Option Cut) : WPlan → AR → AR
| w, .run S ns ks =>
let sizes := ns.map (fun n => n.bag.card)
let y := typical sizes
let wp := witnesses sizes
let endStep : List CNode × Option ℕ := match w with
| .endAt c => ((cutAt y wp c ns).1, some (cutAt y wp c ns).2)
| .whole _ => (ns, none)
let preStep : List CNode × ℕ × Option ℕ := match pre with
| none => (endStep.1, 0, endStep.2)
| some c => ((cutAt y wp c endStep.1).1, (cutAt y wp c endStep.1).2 + 1,
if c.isT1 then endStep.2.map (· + 1) else endStep.2)
let ns' := addV v preStep.2.1 preStep.2.2 preStep.1
let ks' := match w with
| .endAt _ => ks
| .whole ps => applyKids v ps ks
.run S ns' ks'
def applyKids (v : ℕ) : List (Option WPlan) → List AR → List AR
| [], ks => ks
| _ :: _, [] => []
| p :: ps, k :: ks => applyOpt v p k :: applyKids v ps ks
def applyOpt (v : ℕ) : Option WPlan → AR → AR
| none, k => k
| some p, k => processRun v none p k
end
/-- Apply a plan to the run at the end of the path. -/
def applyAt (v : ℕ) : Plan → AR → AR
| .att c chain M, .run S ns ks =>
let sizes := ns.map (fun n => n.bag.card)
let y := typical sizes
let wp := witnesses sizes
let cutRes : List CNode × ℕ := match c with
| none => (ns, ns.length - 1)
| some ct => cutAt y wp ct ns
.run S (addJunk cutRes.2 (branchRT v chain M) cutRes.1) ks
| .top pre w, r => processRun v pre w r
/-- Modify the `i`-th element of a list. -/
def modifyNth {α : Type} (f : α → α) : ℕ → List α → List α
| _, [] => []
| 0, a :: l => f a :: l
| i + 1, a :: l => a :: modifyNth f i l
/-- Walk down the path (indices of kids) and apply the plan. -/
def applyRun (v : ℕ) (p : Plan) : List ℕ → AR → AR
| [], r => applyAt v p r
| i :: rest, .run S ns ks => .run S ns (modifyNth (applyRun v p rest) i ks)
/-- Apply an introduce plan (found in `introPlans v N (t.char B)` at `path`) to the real tree `t`: locate the run at
`path` in the *analysis* of `t`; cut the chain(s) at the witnesses of the typical sequence (a first-type cut
duplicates a node; second-type cuts assign the entries between two witnesses to the side where they are dominated);
add `v` to the bags of the region; or hang the new branch (bags = the chain sets, and `M ∪ {v}` for the leaf).
Python: `reference/real.py: apply_plan`. (`N` is unused: the plan already encodes everything.) -/
def applyPlan (v : ℕ) (_N B : Finset ℕ) (path : List ℕ) (p : Plan) (t : RT) : RT :=
(applyRun v p path (analyze B t)).toRT
/-- The introduce step of the realisation: the first plan whose result is dominated by the target. -/
def realIntro (kmax v : ℕ) (N B : Finset ℕ) (t : RT) (target : CT) : Option RT :=
((CT.introPlans v N (t.char B)).find?
(fun r => domCB (CT.norm r.2.2) target && decide ((CT.norm r.2.2).maxEntry ≤ kmax))).map
(fun r => applyPlan v N B r.1 r.2.1 t)
/-! ## phase B: merging two real trees along lattice paths (join) -/
/-- A monotone lattice path over the exact size sequences `sa`, `sb` whose `τ`-sum minus `|S|` is dominated by
`want` (first found; Python `find_path`). -/
def findPath (sa sb : List ℕ) (c : ℕ) (want : List ℕ) : Option (List (ℕ × ℕ)) :=
((latticeStates sa sb).find? (fun s => domB (s.1.map (· - c)) want)).map (fun s => s.2.reverse)
/-- The merged chain along a path: bag = union of the two bags; junk of a node of either side at its first visit. -/
def mergeChain (na nb : List CNode) : Option (ℕ × ℕ) → List (ℕ × ℕ) → List CNode
| _, [] => []
| prev, (i, j) :: rest =>
let newI := prev.elim true (fun p => decide (p.1 ≠ i))
let newJ := prev.elim true (fun p => decide (p.2 ≠ j))
let a := na.getD i ⟨∅, []⟩
let b := nb.getD j ⟨∅, []⟩
⟨a.bag ∪ b.bag, (if newI then a.junk else []) ++ (if newJ then b.junk else [])⟩ ::
mergeChain na nb (some (i, j)) rest
mutual
/-- Merge two analysed runs along the target run tree `target` (a join option): a lattice path per run. -/
def mergeAR : AR → AR → CT → Option AR
| .run S na ka, .run _ nb kb, .node _ ty tk =>
match findPath (na.map (fun n => n.bag.card)) (nb.map (fun n => n.bag.card)) S.card ty with
| none => none
| some path => (mergeKids ka kb tk).map (fun ks => .run S (mergeChain na nb none path) ks)
def mergeKids : List AR → List AR → List CT → Option (List AR)
| [], [], [] => some []
| a :: as, b :: bs, t :: ts => (mergeAR a b t).bind fun r => (mergeKids as bs ts).map (r :: ·)
| _, _, _ => none
end
/-- Merge two real trees whose characteristics have the same shape, along lattice paths chosen per run so that the
`τ`-sums are dominated by the run sequences of the *join option* `target`. `none` if some run has no such path.
Python: `merge_runs`. -/
def mergeReal (B : Finset ℕ) (ta tb : RT) (target : CT) : Option RT :=
(mergeAR (analyze B ta) (analyze B tb) target).map AR.toRT
/-- The join step of the realisation: the first option of `joinC` of the actual characteristics that is dominated by
the target, merged (Python `realize_join`). -/
def realJoin (kmax : ℕ) (B : Finset ℕ) (ta tb : RT) (target : CT) : Option RT :=
((CT.joinC kmax (ta.char B) (tb.char B)).find? (fun d => domCB d target)).bind (mergeReal B ta tb)
/-! ## phase B: extraction -/
/-- Build a real decomposition of `nt` whose characteristic is dominated by the table entry `target`. -/
def extract (adj : Adj) (k : ℕ) : NT → CT → Option RT
| .leaf, _ => some (.node ∅ [])
| .forget x c, target =>
(tables adj k c).findSome? (fun cq => if CT.forgetC x cq = target then extract adj k c cq else none)
| .intro v c, target =>
(tables adj k c).findSome? (fun cq =>
if target ∈ CT.introC (k + 1) v (nbrs adj v c.bag) cq then
(extract adj k c cq).bind (fun t => realIntro (k + 1) v (nbrs adj v c.bag) c.bag t target)
else none)
| .join a b, target =>
(tables adj k a).findSome? (fun ca => (tables adj k b).findSome? (fun cb =>
if target ∈ CT.joinC (k + 1) ca cb then
(extract adj k a ca).bind (fun ta => (extract adj k b cb).bind (fun tb =>
realJoin (k + 1) a.bag ta tb target))
else none))
/-! ## Kloks: from a rooted decomposition to a nice one -/
def forgetMany (l : List ℕ) (t : NT) : NT := l.foldl (fun acc x => .forget x acc) t
def introMany (l : List ℕ) (t : NT) : NT := l.foldl (fun acc x => .intro x acc) t
mutual
/-- A nice tree with the same root bag: below each child, forget what the child has extra and introduce what it lacks;
join the children (binary, left to right); a leaf becomes `introMany` of its bag over an empty leaf. -/
def niceOf : RT → NT
| .node X ks =>
match niceKids X ks with
| [] => introMany (X.sort (· ≤ ·)) .leaf
| t :: ts => ts.foldl NT.join t
def niceKids (X : Finset ℕ) : List RT → List NT
| [] => []
| k :: ks =>
(let t := niceOf k
introMany ((X \ t.bag).sort (· ≤ ·)) (forgetMany ((t.bag \ X).sort (· ≤ ·)) t)) :: niceKids X ks
end
/-! ## T1 and T2 -/
/-- `G[U]` has a tree decomposition of width `≤ k`. -/
def HasTW (adj : Adj) (U : Finset ℕ) (k : ℕ) : Prop := ∃ t : RT, t.IsTD adj.graph U ∧ t.Width k
/-! ## counting (BP6) -/
end Lax689794Proofs.Chars
end SourceModule8
-- Lax689794Proofs.Wrap.Decompose
section SourceModule41
/-! ### `Lax689794Proofs.Trees.AddEverywhere` -/
/-!
# Adding a vertex to every bag of a nice tree (T2, BP2 part 1)
`NT.addEverywhere v` puts an introduce node above every leaf. Everything is proved by induction on `NT`,
through the local characterisation of `RT.Conn` (`NT.NConn`).
Statement audit note: BP2 states `bag_addEverywhere` without hypotheses. That is false (`t = forget v (intro v leaf)`);
the correct hypotheses are `t.Wf` and `v ∉ t.vs` (`v` occurs nowhere), which is what `addEverywhere_isNiceTD` has.
-/
/-! ### `Lax689794Proofs.Trees.Bridge1Root` -/
/-!
# Rooted trees given by a parent function
Generic graph theory for `Trees/Bridge1`: a tree is the same thing as a finite type with a root, a parent function
`par` (with `par r = r`) and a depth `d` strictly decreasing along `par`. This file proves
* `Rooted.isTree` : the graph `rgraph par` of such data is a tree;
* `exists_rooting` : every finite tree, rooted at any `r`, is of this form;
* `Desc`, `exit` : the descendant relation and the "exit lemma" for connected vertex sets.
-/
/-! ### descendants -/
/-! ### exit lemma and top-connectedness -/
/-! ### `Lax689794Proofs.Trees.Bridge1To` -/
/-!
# Bridge 1, direction (→): an abstract tree decomposition folds into an `RT`
A rooted tree given by a parent function (`Rooted`) with bags whose occurrence sets are connected folds into an
`RT` with `Conn`; then the concept's `TreeDecomposition` is rooted (`exists_rooting`) and folded.
-/
/-! ### `Lax689794Proofs.Trees.Bridge1Paths` -/
/-!
# Nodes of an `RT` as paths
`paths t` is the (finite) set of paths (child indices from the root) of an `RT`; `bagAt t p` the bag at a path.
-/
/-! ### `Lax689794Proofs.Trees.Bridge1From` -/
/-!
# Bridge 1, direction (←): an `RT` decomposition is a `TreeDecomposition`
The abstract tree lives on the nodes-as-paths of the `RT` (`RT.paths`); the parent of a path drops its last step.
-/
/-! ### `Lax689794Proofs.Trees.Bridge1` -/
/-!
# Bridge 1: `RT ↔ Lax228581.Treewidth.TreeDecomposition`
* `hasTreewidthAtMost_iff_rt` : the concept's `HasTreewidthAtMost` in terms of `RT`.
(→) roots the abstract tree (`exists_rooting`: parent function and depth from the distance to the root) and
folds it into an `RT` by induction on the descendant sets (`exists_rt_sub`); `Conn` follows from the
connectedness of the occurrence sets via the *exit lemma*.
(←) builds the abstract tree on the nodes-as-paths of the `RT` (`RT.paths`), parent = drop the last step;
connectedness of an occurrence set follows from its top element (`RT.top_exists`).
* `hasTreewidthAtMost_prefix` : monotonicity under induced subgraphs on initial segments, via `RT.restrict`.
Files: `Bridge1Root` (parent-function trees), `Bridge1Rt` (basic `RT` facts), `Bridge1To`, `Bridge1Paths`,
`Bridge1From`, `Bridge1Restrict`.
-/
/-! ### `Lax689794Proofs.Trees.WordLayout` -/
/-!
# Nice-decomposition words in arbitrary layout (T2)
`GraphWords.NiceDecomposition` allows *any* topological layout of the nodes (the first child of a node is the node just
before it; the second child of a join is an arbitrary earlier node) and arbitrary junk in the unused fields of a record.
`NT.encode` produces only one canonical layout. So the word format is read by `ofWord`, which ignores the junk and the
layout, and everything in this file is proved for an *arbitrary* word `D` satisfying `Lay n D` (the graph-independent
half of `NiceDecomposition`).
Notation: `N = nodeCount D`; `bagN n D i` is `bagAt n D i` with vertices as naturals; `ofWord D i` is the nice tree
rooted at node `i`; `desc D i` the set of nodes of that subtree.
-/
/-! ## bags as sets of naturals -/
/-! ## the layout conditions -/
/-! ## the tree read off a word -/
/-! ### `Lax689794Proofs.Trees.WordDesc` -/
/-!
# The subtree of a node of a word in arbitrary layout (T2)
`desc D i` (the nodes below `i`) satisfies: it is closed under children, contained in `[0, i]`, transitive, its members
are linearly ordered along parent chains, the two subtrees of a join are disjoint, and `desc D (N-1)` is everything.
All from `Lay` (the unique parent).
-/
/-! ### `Lax689794Proofs.Trees.WordTree` -/
/-!
# The nice tree read off a word (T2)
For a word `D` with `Lay n D`, `ofWord D i` is a well-formed nice tree whose root bag is `bagAt i`, whose nodes
correspond to `desc D i`, and whose `RT.Conn` is the conjunction of the local conditions `Loc` on those nodes.
-/
/-! ### `Lax689794Proofs.Trees.WordConn` -/
/-!
# Connectedness of occurrence sets in the word tree (T2)
`ConnOn D S`: the set `S` of nodes is nonempty and any two of its members are joined by a chain of tree edges
staying in `S`. We prove, for a word with `Lay n D`:
* `Lay.loc_of_connOn`: if all the occurrence sets are connected, the local conditions `Loc` hold (a *cut* argument:
the subtree below a node `c` is left only through `c`);
* `Lay.connOn_of_loc`: conversely, the local conditions give connected occurrence sets (a *gluing* induction).
-/
/-! ## the cut argument -/
/-! ## the gluing argument -/
/-! ### `Lax689794Proofs.Trees.WordGraph` -/
/-!
# The word tree as a `SimpleGraph` (T2)
* `Lay.isTree`: `treeGraph D` is a tree (each node but the last has one parent, which is later; count the edges);
* `Lay.connected_iff`: connectedness of an induced subgraph of `treeGraph D` is `ConnOn`.
-/
/-! ### `Lax689794Proofs.Trees.WordBridge` -/
/-!
# `NiceDecomposition` of a word in arbitrary layout ↔ `IsNiceTD` of the tree it reads (T2)
For a word with `Lay n D` (this is the layout half of `NiceDecomposition`), the remaining fields of
`NiceDecomposition G w D` hold iff `ofWord D (N - 1)` is a nice tree decomposition of `G` of width `≤ w`.
-/
/-! ### `Lax689794Proofs.Trees.EncodeReads` -/
/-!
# The canonical word `NT.encode` (T2)
`Reads D b t`: the records of `D` from node `b` on are `NT.recs b t`. `NT.encode t` reads `t` at `0`.
-/
/-! ### `Lax689794Proofs.Trees.Bridge2` -/
/-!
# Bridge 2: nice trees and `GraphWords.NiceDecomposition` (T2)
-/
/-! ### parents in the canonical layout -/
/-! ### `Lax689794Proofs.Wrap.Decompose` -/
section
/-!
# The vertex-by-vertex wrapper (C8a)
* `hasTW_mono` : `HasTW` is monotone under induced subgraphs;
* `Adj.SymmOn` : the symmetry hypothesis on adjacency that the tables need (see `Wrap/NOTES.md`);
* `ImproveSpec adj W` : the conclusion of `improve_correct` for all vertex sets `U ⊆ W` (an explicit hypothesis, so
that the wrapper is proved independently of the tables);
* `decompose_correct`, `decompose_words` : the wrapper's specification on `Adj` / on graphs on `Fin n`.
-/
namespace Lax689794Proofs.Chars
open Lax689794Proofs.Trees Lax689794Proofs.Trees.NT
/-- The adjacency function is symmetric on the vertex set `W`. -/
def Adj.SymmOn (adj : Adj) (W : Finset ℕ) : Prop := ∀ u ∈ W, ∀ v ∈ W, adj u v = adj v u
end Lax689794Proofs.Chars
end
end SourceModule41
-- Lax689794Proofs.Wrap.CompressSize
section SourceModule58
/-! ### `Lax689794Proofs.Wrap.CompressDefs` -/
section
namespace Lax689794Proofs.Trees
/-- Dissolve the kids whose bag is inside the parent's bag (their kids move up). -/
def flatKids (X : Finset ℕ) : List RT → List RT
| [] => []
| .node Y ls :: rest => if Y ⊆ X then ls ++ flatKids X rest else .node Y ls :: flatKids X rest
mutual
/-- Dissolve, bottom-up, every node whose bag is contained in its parent's bag. -/
def compress : RT → RT
| .node X ks => .node X (flatKids X (compressL ks))
def compressL : List RT → List RT
| [] => []
| k :: ks => compress k :: compressL ks
end
end Lax689794Proofs.Trees
end
/-! ### `Lax689794Proofs.Wrap.CompressTD` -/
/-!
# `compress` preserves tree decompositions and widths, and produces a compressed, connected tree (P0)
* `verts_compress`, `bags_compress_sub`, `bags_compress_cover` : vertex set unchanged, bags only lose,
every lost bag was inside a surviving one;
* `compress_conn_comp` : `t.Conn → (compress t).Conn ∧ Comp (compress t)`;
* `compress_isTD`, `compress_width`.
-/
/-! ### connectedness and compressedness -/
/-! ### `Lax689794Proofs.Wrap.CompressSize` -/
/-!
# `compress`: the decomposition facts and the size bound (P0)
* `compress_isTD`, `compress_width` ;
* `size_le_of_comp` : a connected, compressed tree has at most `1 + |V \ root bag|` nodes (every non-root node owns
the vertices of its bag that are not in its parent's bag; connectedness makes these sets disjoint);
* `compress_size_le` : `(compress t).size ≤ |V(t)| + 1` for a connected `t`.
-/
end SourceModule58
-- Lax689794Proofs.Wrap.ImproveC
section SourceModule59
/-! ### `Lax689794Proofs.Wrap.Improve` -/
/-! ### `Lax689794Proofs.Wrap.ImproveC` -/
section
/-!
# `improveC`, `decomposeC`: the polynomial-size wrapper (work package P0)
`improveC` is `improve` with a `compress` between `extract` and `niceOf`. The machine layer runs
`improveC` / `decomposeC` (not `improve` / `decompose`): the latter feed an arbitrary extracted tree to the
next round, so the nice trees grow by a factor ≈ 2.2 per round.
* `improveC_correct` : as `improve_correct`, plus the size bound `(|U| + 2)²` of the result;
* `decomposeC_correct_final`, `decomposeC_words_final` : as for `decompose` (same conclusions);
* `decomposeC_size_le` : after round `i` the nice tree has at most `(i + 2)²` nodes.
-/
namespace Lax689794Proofs.Chars
open Lax689794Proofs.Trees Lax689794Proofs.Trees.NT
/-- **`improveC`**: `improve` with the extracted decomposition compressed before Kloks' conversion. -/
def improveC (adj : Adj) (k : ℕ) (nt : NT) : Option NT :=
match tables adj k nt with
| [] => none
| c :: _ => (extract adj k nt c).map (fun t => niceOf (compress t))
/-- The vertex-by-vertex wrapper with `improveC`. -/
def decomposeC (adj : Adj) (k : ℕ) : ℕ → Option NT
| 0 => some .leaf
| i + 1 => (decomposeC adj k i).bind (fun t => improveC adj k (NT.addEverywhere i t))
end Lax689794Proofs.Chars
end
end SourceModule59
/-
Source attribution
The treewidth algorithm and its correctness proof are from yuvalyitz/treewidth-lax, commit b6743cf02087f552d8f023581f4718e68c42e444. The word-RAM semantics are from lax-archive/lax-submissions, commit 9394e531cc51cb67a0214bca3f9264dfe97ba5c7, word-ram/. The local streaming header and uniform output bounds extend these sources. Project-local proof tactics have been expanded into ordinary Lean proof steps.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
Source